箭头函数

29 阅读1分钟

特点

  1. 语法简洁
    • 省略function关键字
    () => {}
    
    • 单行可省略括号
    a => a * 2
    
    • 单行返回值可以省略
    (a, b) => a + b
    
    • 返回对象需加括号
    () => ({})
    
  2. 无独立的this绑定
    • 继承外层作用域的this
  3. 不可作为构造函数
    • 无法用new调用,会报错
    • 没有prototype属性,无法用于原型继承或实例化
  4. 无arguments对象
    • 需要用剩余参数替代
    (...args) => console.log(args)
    
    普通函数
    function a () {
        console.log(arguments) // arguments 类数组对象
    }
    
    访问arguments会引用外层函数的arguments;
    function a() {
        return () => console.log(arguments) // 拿到外层普通函数的 arguments 类数组对象
    }
    
  5. 不能用做生成器
    • 不可使用yield关键字

适用场景

- 需要固定this的上下文
    - 如回调函数 / map / filter 等数组方法
- 替代匿名函数
    - 简化代码
- 避免this绑定问题

实例对比

// 普通函数
function add(a,b) { return a + b}
const obj = {
    count: 1,
    increment: function () {
        setTimeout(function () {
            this.count++ // 错误,这里this 指向window
        }, 100)
    }
}

// 箭头函数
const add = (a, b) => a + b
const obj = {
    count: 1,
    increment: function () {
        setTimeout(() => {
            this.count++ //  2  正确,this指向increment上下文
        }, 100)
    }
}