最常用且兼容性最好的防护方式是用 instanceof 判断 this 是否为构造函数实例,若不是则自动补 new;es6 推荐 new.target 检测调用方式,语义清晰、避免递归;严格模式可使漏 new 调用立即报错。

用 instanceof 判断 this 是否为构造函数实例
在构造函数开头检查 this 是否属于当前构造函数的实例,如果不是,就主动用 new 重新调用一次。这是最常用、兼容性最好的防护方式。
- 写法示例:
function Person(name) {
if (!(this instanceof Person)) {
return new Person(name);
}
this.name = name;
} - 原理:非 new 调用时,this 指向全局或 undefined,一定不满足 this instanceof Person,于是自动补上 new
- 注意:该方法对箭头函数无效(箭头函数没有自己的 this 和 prototype),所以构造函数必须是普通函数
用 new.target 检测是否通过 new 调用
new.target 是 ES6 引入的元属性,只要函数是通过 new 调用的,它就指向当前构造函数;否则值为 undefined。适合现代环境且语义更清晰。
- 写法示例:
function Car(brand) {
if (!new.target) {
throw new Error('Car must be called with new');
}
this.brand = brand;
} - 优势:比 instanceof 更早触发判断,避免执行到中间才出错;也避免了递归调用风险(比如 new Person() 内部又调 Person())
- 兼容性:Chrome 46+、Firefox 41+、Safari 9+、Node.js 4.0+ 均支持;旧环境需 Babel 转译
配合严格模式增强报错效果
在构造函数顶部加上 'use strict',能让漏掉 new 的调用直接抛错,而不是静默污染全局。虽然不能自动修复,但能快速暴露问题。
- 非严格模式下:Person('Tom') 中的 this 指向 window,this.name = 'Tom' 会挂到全局,不易察觉
- 严格模式下:this 为 undefined,执行 this.name = 'Tom' 会立即报 TypeError: Cannot set property 'name' of undefined
- 推荐组合使用:'use strict' + new.target,兼顾开发提示与运行时保护
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











