← 返回完整题库
JavaScript中等

如何让一个构造函数只能被 new 调用,不能直接调用?

参考答案

ES6 class

class 本身就有此约束:直接调用抛 TypeError: Class constructor X cannot be invoked without 'new'。

传统函数

function F() {
  if (!new.target) throw new TypeError('必须用 new 调用');
  // 或用 this instanceof F 判断(不当,call 绑定对象可绕过)
}

其他方式

if (this === undefined || this === window) throw ...(严格模式下 this 为 undefined 更可靠);或用 new.target(ES6 首选),也可返回一个只暴露工厂函数的模块。

推荐 new.target:语义准确、不受 call/apply 影响。

本题来自 计算机知识面试题库,共 921 道题。