// 定义一个箭头函数
const ArrowFunction = () => {
this.value = 42;
};
// 尝试用 new 关键字调用箭头函数
const instance = new ArrowFunction(); // TypeError: ArrowFunction is not a constructor
没有 this
绑定:箭头函数不会创建自己的 this
。在箭头函数中,this
是在定义时从其外层作用域继承的,而不是在调用时绑定的。
没有 [[Construct]]
内部方法:传统函数(普通函数)有一个 [[Construct]]
内部方法,使它们能够被用作构造函数并与 new
关键字一起使用。箭头函数没有这个内部方法,因此不能用作构造函数。
普通函数可以用作构造函数,并且 this
绑定到新创建的实例对象上。
// 定义一个普通函数
function RegularFunction() {
this.value = 42;
}
// 使用 new 关键字调用普通函数
const instance = new RegularFunction();
console.log(instance.value); // 输出 42
[[Construct]]
内部方法,并且 this
绑定机制不同。用 new
关键字调用箭头函数会抛出 TypeError
。this
在调用时绑定到新创建的实例对象上。