最推荐使用new.target判断构造函数调用方式:new调用时指向构造函数,直接调用时为undefined;兼容旧环境可检查this instanceof 构造函数;严格模式下this为undefined更易检测;箭头函数无new.target且不能作为构造函数。

可以在构造函数内部检查 this 是否为该构造函数的实例,如果不是(即被当作普通函数调用),就主动抛出错误。
使用 new.target 判断调用方式
new.target 是 ES6 引入的元属性,在函数中访问时:
- 通过
new调用时,new.target指向当前构造函数; - 直接调用时,
new.target为undefined。
这是最推荐、最简洁的方式:
function Person(name) {
if (!new.target) {
throw new Error('Person 必须使用 new 调用');
}
this.name = name;
}
// ✅ 正确
const p1 = new Person('Alice');
// ❌ 抛出错误:Person 必须使用 new 调用
// const p2 = Person('Bob');
兼容旧环境:检查 this 的原型链
在不支持 new.target 的环境中(如 IE),可退而求其次,检查 this 是否是当前函数的实例:
- 若直接调用,
this通常指向全局对象(非严格模式)或undefined(严格模式); - 此时
this instanceof Person为false,且this不具备预期结构。
注意:该方式有局限性(比如 this 被显式绑定为某个对象时可能误判),但对多数场景够用:
function Person(name) {
if (!(this instanceof Person)) {
throw new Error('Person 必须使用 new 调用');
}
this.name = name;
}
结合严格模式增强安全性
在严格模式下,普通函数调用时 this 为 undefined,能更可靠地触发判断:
'use strict';
function Person(name) {
if (!new.target) {
throw new Error('Person 必须使用 new 调用');
}
this.name = name;
}
严格模式还能避免意外绑定到全局对象,让错误更早暴露。
箭头函数不能替代构造函数
箭头函数没有自己的 new.target 和 this 绑定,**不能用作构造函数**,尝试 new 调用会直接报错:TypeError: xxx is not a constructor。所以它天然“防误调”,但也不适用于需要实例化的场景。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











