JavaScript 中构造函数怎么不使用 new
在 javascript 中,构造函数不使用 new 关键字时,函数体内的 this 会指向全局对象(浏览器环境下的 window)或报错(严格模式下),导致属性被挂载到全局作用域而非新实例。要避免这种错误并实现无 new 调用,最直接的方法是在构造函数内部检测 this 的归属:如果 this 不是当前构造函数的实例,则手动使用 new 重新调用自身并返回结果。

如何检测并自动修正非 new 调用
通过检查 this instanceof Constructor 可以判断调用方式。若为假,说明是普通函数调用,此时执行 return new Constructor(...arguments) 即可强制转为正确的实例化流程,确保返回值始终是预期的对象实例。

function User(name, age) {
if (!(this instanceof User)) {
return new User(name, age);
}
this.name = name;
this.age = age;
}
// 测试用例
const u1 = new User('Alice', 25); // 正常 new
const u2 = User('Bob', 30); // 无 new,自动修正
console.log(u1 instanceof User); // true
console.log(u2 instanceof User); // true
console.log(u1 === u2); // false
基于原型链继承中的具体调用问题
当子类构造函数通过 super() 调用父类构造函数时,如果父类未做 new 保护,子类的 this 同样会被错误地指向全局对象。因此,在构建继承体系时,父类必须包含上述的 instanceof 检查逻辑,否则子类的实例将无法正确继承父类属性。
立即学习“Java免费学习笔记(深入)”;


















