Skip to content

箭头函数

题目1: 箭头函数与普通函数的区别是什么?

答案: 箭头函数与普通函数的主要区别包括:

  1. 语法更简洁
  2. 没有自己的this,会捕获其所在上下文的this值
  3. 没有arguments对象
  4. 不能用作构造函数(不能用new关键字调用)
  5. 没有prototype属性
  6. 不能用作生成器函数(不能使用yield关键字)

扩展:

javascript
// 普通函数
function add(a, b) {
    return a + b;
}

// 箭头函数
const add = (a, b) => a + b;

题目2: 如何在箭头函数中使用this?

答案: 箭头函数没有自己的this,它会捕获其所在上下文的this值。这意味着箭头函数中的this与封闭词法作用域的this相同。

扩展:

javascript
const obj = {
    name: 'John',
    greet: function() {
        setTimeout(() => {
            console.log(`Hello, ${this.name}`);
        }, 1000);
    }
};

obj.greet(); // 输出: Hello, John

题目3: 箭头函数可以用作构造函数吗?为什么?

答案: 不可以。箭头函数不能用作构造函数,因为:

  1. 箭头函数没有自己的this,无法绑定到新创建的对象上
  2. 箭头函数没有prototype属性,无法设置原型链
  3. 箭头函数不能使用new.target

扩展:

javascript
const Person = (name) => {
    this.name = name;
};

const john = new Person('John'); // TypeError: Person is not a constructor

题目4: 箭头函数中的arguments对象是如何处理的?

答案: 箭头函数没有自己的arguments对象。如果在箭头函数中访问arguments,它会捕获外围函数的arguments对象。如果需要使用类似arguments的功能,可以使用剩余参数(rest parameters)。

扩展:

javascript
function outer() {
    const inner = () => {
        console.log(arguments);
    };
    inner();
}

outer(1, 2, 3); // 输出: { '0': 1, '1': 2, '2': 3 }

// 使用剩余参数
const sum = (...args) => args.reduce((a, b) => a + b, 0);
console.log(sum(1, 2, 3)); // 输出: 6

题目5: 箭头函数在什么情况下不适合使用?

答案: 箭头函数在以下情况下不适合使用:

  1. 作为对象的方法,特别是需要动态this的情况
  2. 作为构造函数
  3. 需要使用arguments对象时
  4. 需要使用函数提升时
  5. 需要使用yield关键字时(生成器函数)

扩展:

javascript
const obj = {
    value: 0,
    increment: () => {
        this.value++; // 这里的this不是指向obj
    }
};

obj.increment();
console.log(obj.value); // 输出: 0,而不是预期的1