最直接有效的办法是在构造函数内部加防护机制。可通过严格模式报错、instanceof自动补new、new.target检测或改用class语法,防止不带new调用导致的全局污染和隐式赋值问题。

最直接有效的办法是在构造函数内部加防护机制,而不是依赖开发者自觉写 new。不加 new 时,this 会指向全局对象(如 window 或 globalThis),容易污染全局、产生隐式赋值,甚至返回 undefined,造成难以排查的 bug。
用严格模式报错拦截
在函数第一行写 'use strict',此时未用 new 调用会导致 this 为 undefined,后续对 this.xxx = xxx 赋值就会立即抛出 TypeError:
- function Person(name) { 'use strict'; this.name = name; }
- Person('Alice') // TypeError: Cannot set property 'name' of undefined
用 instanceof 自动补 new
判断当前 this 是否为该构造函数的实例,不是就手动调用一次 new 并返回新对象:
- function Person(name) { if (!(this instanceof Person)) return new Person(name); this.name = name; }
- Person('Bob').name // 'Bob' —— 不写 new 也能得到正确实例
- new Person('Charlie').name // 同样有效,兼容两种写法
用 new.target 检测调用方式
new.target 在通过 new 调用时指向构造函数本身,否则为 undefined。可据此强制校验或抛出自定义错误:
- function Person(name) { if (!new.target) throw new Error('Person must be called with new'); this.name = name; }
- Person('David') // 抛出明确错误,提示清晰
现代写法推荐:改用 class 语法
ES6 的 class 构造器天然禁止不带 new 的调用,直接报 TypeError: Class constructor Person cannot be invoked without 'new':
- class Person { constructor(name) { this.name = name; } }
- Person('Eve') // ❌ 立即报错,无需额外防护
- new Person('Eve') // ✅ 正常工作











