面试题:️如果 new 一个箭头函数会怎么样?

使用 new 操作符来调用一个箭头函数会抛出一个 TypeError 错误。

箭头函数不能用作构造函数。

1. 直接示例

const ArrowFunc = () => {
  console.log('I am an arrow function');
};

// 尝试用 new 调用
new ArrowFunc(); // TypeError: ArrowFunc is not a constructor

2. 为什么会这样?

这是由箭头函数的设计和内部机制决定的:

  • 没有 [[Construct]] 方法:在 JavaScript 的规范中,一个函数对象要能被 new 调用,它必须实现一个内部方法 [[Construct]]。普通函数(使用 function 关键字定义)有这个方法,而箭头函数没有
  • 没有自己的 thisnew 操作符的核心步骤之一是创建一个新对象,并将这个新对象绑定为函数内部的 this。但箭头函数不绑定自己的 this,它的 this 是词法继承自外层作用域的。这与 new 的机制是根本冲突的。
  • 没有 prototype 属性:普通函数有一个
    const normalFunc = function() {};
    console.log(normalFunc.prototype); // 输出一个对象
    
    const arrowFunc = () => {};
    console.log(arrowFunc.prototype); // undefined

3. 与普通函数的对比

// 普通函数:可以作为构造函数
function Person(name) {
  this.name = name;
}
const person = new Person('Alice');
console.log(person.name); // 'Alice'

// 箭头函数:不能作为构造函数
const PersonArrow = (name) => {
  this.name = name; // 即使不报错,this 也不指向新对象
};
// new PersonArrow('Bob'); // TypeError: PersonArrow is not a constructor

4. 总结

  • 结果new 一个箭头函数会抛出 TypeError: XXX is not a constructor
  • 原因
    1. 箭头函数缺少 [[Construct]] 内部方法。
    2. 箭头函数不绑定自己的 this,与 newthis 绑定机制冲突。
    3. 箭头函数没有 prototype 属性。
  • 设计意图:ES6 引入箭头函数的主要目的是提供一种更简洁的语法来编写不绑定 this 的函数,特别适合用作回调。它从设计上就排除了作为构造函数的可能性。

因此,在代码中应避免尝试用 new 来调用箭头函数。如果需要创建对象实例,应该使用传统的 function 构造函数或 ES6 的 class 语法。

THE END
喜欢就支持一下吧
点赞9 分享