箭头函数为什么没有构造函数?
箭头函数没有构造函数,是因为它本质上是一个简化的匿名函数,并且它的 this
绑定行为与普通函数不同。以下是具体原因:
1. 箭头函数没有 prototype
普通函数可以作为构造函数来创建对象,因为它们有 prototype
,但箭头函数没有。
示例
function Person(name) {
this.name = name;
}
let p1 = new Person("张三"); // ✅可以使用 new 创建对象
console.log(p1.name); // "张三"
const ArrowPerson = (name) => {
this.name = name;
};
let p2 = new ArrowPerson("李四"); // ❌ 报错:ArrowPerson is not a constructor
🔹 解析
Person 有 prototype,可以用 new 创建对象。
ArrowPerson 没有 prototype,不能用 new。
- 箭头函数的 this 绑定不可变
普通函数的 this 指向调用它的对象,但箭头函数的 this 是定义时绑定的,永远不会变。
示例
function Person(name) {
this.name = name;
this.sayHello = function() {
console.log("Hello, " + this.name);
};
}
let p = new Person("张三");
p.sayHello(); // "Hello, 张三" ✅ this 绑定到 `p`
const ArrowPerson = (name) => {
this.name = name; // ❌ this 不指向 ArrowPerson
};
let ap = new ArrowPerson("李四"); // ❌ 报错
🔹 解析
Person 里的 this 绑定到 p,所以能正确调用 sayHello()。
ArrowPerson 里的 this 不指向 ArrowPerson,而是指向外层作用域的 this,所以无法创建对象。
- 箭头函数适合回调,不适合作构造函数
因为箭头函数不会改变 this,所以它常用于回调函数、map()、setTimeout() 等场景,而不适合用作构造函数。
示例
let obj = {
name: "张三",
sayHello: function() {
setTimeout(() => {
console.log("Hello, " + this.name); // ✅ this 仍然指向 obj
}, 1000);
}
};
obj.sayHello(); // "Hello, 张三"
🔹 解析
由于 setTimeout() 里的箭头函数不会改变 this,所以 this.name 仍然指向 obj,输出正确。
总结
普通函数 | 箭头函数 |
---|---|
有 prototype,可作为构造函数 | 没有 prototype,不能作为构造函数 |
this 指向调用者,可变 | this 定义时绑定,不可变 |
适合作为对象方法、构造函数 | 适合回调函数、数组方法(map、filter) |
适用于 new 关键字创建对象 | 不能用 new |