实现说明
逻辑集中在类 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);