ES6 简化语法的使用
1、let 关键字
let
关键字 没有变量提升
// 和 var 关键字的用法基本一样
// let food = '西兰花'
// food = '西兰花炒蛋'
// console.log(food);
// 没有变量提升
/*
变量声明 会提升到 当前作用域的顶端
*/
// console.log(food)
// var food = '西兰花'
// let 不会提升
console.log(food)
let food = '西兰花'
2、模板字符串
- 使用 ``(反引号) 包裹文本
- 在需要替换的位置使用 ${} 占位,并填入内容即可
let name = "花花"
let food = "西兰花"
let city = "武汉"
let temStr = `我的名字是:${
name} 我喜欢的东西是:${
food} 我所在的城市是:${
city}`
console.log(temStr)
3、对象的简化赋值
- 如果属性名 和 变量名相同,可以简写
- 方法可以省略 function 关键字
let name = "小黑"
let city = "武汉"
// 方法可以省略 function 关键字
let person = {
name,// name: name,
city,// city: city
// saHello: function () {
// console.log('你好!')
// }
saHello() {
console.log('你好!')
}
}
console.log(person)
person.saHello()
4、箭头函数
function省略掉,替换为 =>
参数只有一个时,可以省略 ()
函数体只有一行时,可以省略 {}
函数体只有一行,并且有返回值时,如果省略了 {} 必须省略 return
// 无参数,一行,无返回值的函数
// let func1 = function () {
// console.log('hello ITheima')
// }
let func1 = () => console.log('hello IT')
func1()
// 1个参数,一行,无返回值函数
// let func2 = function (p1) {
// console.log(p1)
// }
let func2 = p1 => console.log(p1)
func2('你好')
// 2个参数,多行,无返回值函数
// let func3 = function (p1, p2) {
// console.log(p1)
// console.log(p2)
// }
let func3 = (p1, p2) => {
console.log(p1)
console.log(p2)
}
func3('你好', '欢迎你的到来')
// 无参数,一行,有返回值的函数
// let func4 = function () {
// return 'hello ITheima'
// }
let func4 = () => 'hello IT'
console.log(func4())
// 1个参数,一行,有返回值的函数
// let func5 = function (p1) {
// return p1 + 'hello ITheima'
// }
let func5 = p1 => p1 + 'hello IT'
console.log(func5('武汉'))
// 2个参数,多行,有返回值的函数
// let func6 = function (p1,p2) {
// console.log(p1, p2)
// return p1 + p2 + 'hello ITheima'
// }
let func6 = (p1, p2) => {
console.log(p1, p2)
return p1 + p2 + 'hello IT'
}
console.log(func6('武汉', '加油'))
5、箭头函数的 this
关键字
- 创建时的 this 是谁 运行的时候 this 就是谁
let person = {
name: '花花',
food: '西兰花',
saHi() {
// console.log(this)
// 保存 this
// let that = this
// setTimeout(function () {
// // console.log(this)
// console.log(that)
// }, 100)
setTimeout(() => {
console.log(this)
}, 100)
}
}
// 谁点出来的 就是谁
person.saHi()
ps:这些是比较常用的简化语法,它可以减少我们的代码的书写量,从而提高开发效率,并且语义明确,值得掌握哟!(づ ̄ 3 ̄)づ