1. 箭头函数 基本语法
const fn = () => {
console.log(123)
}
fn()
const fn = (x) => {
console.log(x)
}
fn(1)
2. 只有一个形参的时候,可以省略小括号
const fn = x => {
console.log(x)
}
fn(1)
3. 只有一行代码的时候,我们可以省略大括号
const fn = x => console.log(x)
fn(1)
4. 只有一行代码的时候,可以省略return
const fn = x => x + x
console.log(fn(1))
5. 箭头函数可以直接返回一个对象
const fn = (name) => ({ name: name })
console.log(fn('张三'))
6.箭头函数不会创造自己的this,它只会从自己的作用域链的上一层沿用this
const fn = () => {
console.log(this) // window
}
fn()
// 对象方法箭头函数 this
const obj = {
uname: '张三',
sayHi: () => {
console.log(this) // window
}
}
obj.sayHi()
const obj = {
uname: '张三',
sayHi: function () {
console.log(this) // obj
let i = 10
const count = () => {
console.log(this) // obj
}
count()
}
}
obj.sayHi()
总结:
1. 箭头函数属于表达式函数,因此不存在函数提升
2. 箭头函数只有一个参数时可以省略圆括号 `()`
3. 箭头函数函数体只有一行代码时可以省略花括号 `{}`,并自动做为返回值被返回
4. 箭头函数中没有 `arguments`,只能使用 `...` 动态获取实参
5. 箭头函数不会创造自己的this,它只会从自己的作用域链的上一层沿用this