如果new一个箭头函数会怎么样?
参考答案
结论
会报错:TypeError: xxx is not a constructor。箭头函数不能作为构造函数,也不能被 new 调用。
const Arrow = () => {};
new Arrow(); // TypeError: Arrow is not a constructor
为什么
new 调用需要构造函数具备两个能力,箭头函数都没有:
- **
[[Construct]]内部方法**:箭头函数只有[[Call]],没有[[Construct]],因此不能被new。 - **自己的
this与prototype**:new需要创建对象、把this绑定到新对象、并访问F.prototype设置原型链。箭头函数:
- 没有自己的
this(词法继承,无法被new置为新对象); - **没有
prototype属性**(Arrow.prototype === undefined)。
const f = () => {};
f.prototype; // undefined
f.hasOwnProperty('prototype'); // false
与其他函数的对比
| 能力 | 普通函数 | 箭头函数 | class | 方法简写 |
| --- | --- | --- | --- | --- |
| new 调用 | ✅ | ❌ | ✅ | ❌ |
| prototype | ✅ | ❌ | ✅ | ❌ |
| 自己的 this | ✅ | ❌(词法) | ✅ | ✅ |
| arguments | ✅ | ❌ | ✅ | ✅ |
| super | ❌ | ❌ | ✅ | ✅(对象方法) |
| yield(Generator) | ✅ | ❌ | ❌ | ❌ |
相关细节
- **
Reflect.construct(Arrow, [])也会失败**(没有[[Construct]])。 - 箭头函数也**不能用作
extends的父类**(class X extends Arrow会报错)。 - 如果确实需要一个"可 new 的箭头风格"函数,只能用普通函数/class,或者:
class ArrowLike { constructor() { /* ... */ } }
- 箭头函数可以作为普通函数调用、回调、
bind(bind 只影响 this,但箭头函数 this 不变,所以 bind 无效)、call/apply(不改变 this,但会执行)。
一句话
箭头函数不是"更短的函数",而是"没有 this/prototype/arguments 的轻量函数表达式",所以它天然不具备构造能力。