new.target 是 javascript 中用于检测函数是否通过 new 调用的元属性,未使用 new 时为 undefined,可用于强制构造函数必须用 new 调用,在 class 和 function 构造器中均适用,es6+ 环境可靠但不兼容 ie。

在 JavaScript 中,new.target 是一个元属性,它在函数执行时返回当前构造函数的引用;若函数不是通过 new 调用(即作为普通函数调用),则 new.target 为 undefined。利用这个特性,可以有效阻止构造函数被误用为普通函数。
检测 new.target 是否存在
最直接的方式是在函数体开头检查 new.target 是否为 undefined。如果是,说明未通过 new 调用,可抛出错误或提前退出。
- 适用于类(class)和传统 function 构造函数
- ES6+ 环境下可靠,不兼容 IE
- 注意:箭头函数没有自己的
new.target,不可用于构造逻辑
在 class 中强制 new 调用
类的构造器(constructor)天然依赖 new,但若想进一步强化约束(例如防止子类绕过),可在 constructor 中显式校验:
class Person {
constructor(name) {
if (!new.target) {
throw new TypeError('Person must be instantiated with "new"');
}
this.name = name;
}
}
这样即使有人尝试 Person("Alice"),也会立即报错。
在普通函数构造器中应用
对于使用 function 定义的传统构造函数,new.target 同样可用:
function Animal(name) {
if (!new.target) {
throw new Error('Animal must be called with "new"');
}
this.name = name;
this.speak = () => console.log(`${name} makes a sound`);
}
此时 Animal("dog") 报错,而 new Animal("dog") 正常工作。
兼容性与替代方案提示
若需支持老旧环境(如 IE),new.target 不可用,可改用 this instanceof Constructor 判断,但该方式在严格模式下、或当 this 被显式绑定时可能失效。因此,在现代项目中优先使用 new.target 更准确、简洁、无副作用。










