说说你对 new.target 的理解
参考答案
作用
new.target 是函数内部可用的元属性,指向"被 new 调用的那个构造函数";如果函数是普通调用(不带 new),new.target 为 undefined。
function Foo() {
console.log(new.target); // new 调用 → [Function: Foo];普通调用 → undefined
if (!new.target) throw new Error('必须使用 new 调用');
}
new Foo(); // [Function: Foo]
Foo(); // undefined
主要用途
- **强制
new调用**(class 内部就是这么实现的):
function Person(name) {
if (!new.target) return new Person(name); // 或者抛错
this.name = name;
}
- 在继承中判断实际构造器:
class Base {
constructor() { console.log(new.target.name); } // 子类实例化时是子类名
}
class Child extends Base {}
new Child(); // 'Child'
用它可以区分"是谁在实例化",做多态初始化。
- 抽象类模拟:
class Abstract {
constructor() {
if (new.target === Abstract) throw new Error('抽象类不能直接实例化');
}
}
- 工厂/继承场景下的差异化逻辑:
new.target === Foo时执行 A,new.target === Bar时执行 B。
特点
- 只能在函数体内使用(箭头函数没有自己的
new.target,会取外层)。 - 在
class构造器中可用;super()调用时父类构造器里的new.target仍是子类。 - 与
this.constructor的区别:this.constructor可被篡改/继承链影响,new.target是调用时确定的,更可靠。 Reflect.construct(Target, args, newTarget)可以显式指定new.target,用于实现"以 A 的逻辑创建 B 的实例"。
示例:Reflect.construct 控制 new.target
function A() { console.log(new.target.name); }
class B {}
Reflect.construct(A, [], B); // 输出 'B'
一句话
**new.target 让你知道"是不是被 new 调的、被谁 new 的"**,是实现"必须 new"、"抽象类"、继承多态初始化的标准手段。