← 中文资源

简体中文版本

new.target 守卫缺失的 new 调用

普通函数调用不会设置 new.target,构造器据此抛出明确错误;同一检查让抽象基类拒绝直接实例化,而子类实例化不受影响。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

plain call: Bag() requires new
bag ok: true
abstract: Store is abstract
subclass ok: true

实现说明

逻辑集中在类 Store、MemoryStore、ok和函数 Bag里。 守卫条件成立时抛出 TypeError,而不是返回一个假值。

使用要点

  • 守卫 !new.target 命中后立刻用提前的 throw 结束这一轮。
  • 每一步打印都带着自己的标签:plain call:、bag ok:、abstract:。

常见问题

坏输入有失败路径吗?

代码会拒绝继续:抛出 TypeError,此时状态仍可恢复。

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。 文件在加载时定义 Bag。

主签名形如 function Bag(items)

核心语句

throw new TypeError("Bag() requires new");
throw new TypeError("Store is abstract");

代码示例

// Function constructors: detect a missing "new"
function Bag(items) {
  if (!new.target) {
    throw new TypeError("Bag() requires new");
  }
  this.items = items;
}

try {
  Bag(["x"]);
} catch (error) {
  console.log("plain call:", error.message);
}

const bag = new Bag(["x"]);
console.log("bag ok:", bag.items.length === 1);

// Abstract base class: reject direct instantiation, allow subclasses
class Store {
  constructor() {
    if (new.target === Store) {
      throw new TypeError("Store is abstract");
    }
  }
}
class MemoryStore extends Store {}

try {
  new Store();
} catch (error) {
  console.log("abstract:", error.message);
}

console.log("subclass ok:", new MemoryStore() instanceof MemoryStore);