箭头函数=>

82 阅读1分钟

1. 箭头函数与普通函数的区别

  • 语法:更简洁((a, b) => a + b)。
  • this 指向
    • 箭头函数:继承自父级作用域(定义时确定)。
    • 普通函数:取决于调用方式(如callapplynew)。
  • 不可使用的特性
    • arguments对象。
    • 不能使用yield(无法定义生成器函数)。
    • 不能使用new关键字(无[[Construct]]内部方法)。

2. 箭头函数的 this 指向示例

const obj = {
  name: 'Alice',
  sayHi: function() {
    setTimeout(() => {
      console.log(this.name); // ✅ 继承自 sayHi 的 this(obj)
    }, 1000);
  }
};

obj.sayHi(); // 输出: Alice

3. 箭头函数的应用场景

  • 回调函数(如数组方法):
    const numbers = [1, 2, 3];
    const doubled = numbers.map(n => n * 2);
    
  • 简化单行逻辑
    const sum = (a, b) => a + b;
    
  • 需要绑定上下文的场景(避免使用bind)。

4. 箭头函数的限制

  • 无法使用arguments
    const func = () => {
      console.log(arguments); // ❌ 报错
    };
    
  • 不能使用yield(无法定义生成器函数)。
  • 不适合定义对象方法this会指向全局对象):
    const person = {
      age: 30,
      getAge: () => this.age // ❌ this 指向全局/undefined
    };
    

5. 箭头函数的性能

  • 与普通函数执行效率相近,但解析速度可能略快(语法更简洁)。
  • 主要影响在于this绑定的便利性,而非性能优化。

6. 箭头函数的解构参数

const user = { name: 'Bob', age: 25 };
const printInfo = ({ name, age }) => `${name} is ${age} years old`;

printInfo(user); // 输出: "Bob is 25 years old"

7. 箭头函数的返回值

  • 隐式返回:单行表达式无需return
    const square = x => x * x; // 等价于 return x * x
    
  • 返回对象字面量:需用括号包裹:
    const createUser = () => ({ name: 'Alice', age: 30 });