Object.create(instance) 通过了 instanceof,为什么读取私有字段仍报错?

作者:闭包旅人

时间:2026-12-01

浏览:498

用一个计数器拆解 Object.create、instanceof 和类的私有字段检查,并给出复制实例状态的写法。

文章目录

用 Object.create(original) 复制计数器,前两次检查都过了。新对象能通过 instanceof,标签也读得出来。直到第一次取计数值,才碰到 TypeError。问题出在 getter 读私有字段的那一行。

标签读得出来,计数值为什么报错

label 是公开字段,count 是一个返回 #count 的 getter。示例只打印异常的 name,省去不同引擎的报错措辞差异。

class Counter {
  #count;
  label = 'toolbar';

  constructor(start = 0) {
    this.#count = start;
  }

  static hasCount(value) {
    return #count in value;
  }

  get count() {
    return this.#count;
  }

  increment() {
    this.#count += 1;
  }

  copy() {
    return new Counter(this.#count);
  }
}

const original = new Counter(3);
const derived = Object.create(original);

console.log(`instanceof: ${derived instanceof Counter}`);
console.log(`label: ${derived.label}`);
console.log(`has #count: ${Counter.hasCount(derived)}`);
try {
  console.log(derived.count);
} catch (error) {
  console.log(`get count: ${error.name}`);
}
控制台预期输出,instanceof 为 true,能读取 label,私有字段检查为 false,读取 count 抛出 TypeError
第一段代码的预期控制台输出

Object.create(original) 把 original 设为新对象的原型。读 derived.label 时,沿原型链在 original 上找到了 toolbar。这里的 instanceof 也会沿链查找。只要链上有 Counter.prototype,结果就是 true。

getter 里的 this 仍然是 derived

读 derived.count 时,JavaScript 沿原型链在 Counter.prototype 上找到 getter,并以最初的接收者 derived 作为 this 调用它。接下来的 this.#count 只检查 derived 自身。构造时安装在 original 上的私有字段帮不上忙,所以 getter 抛出了 TypeError。

原型链从 derived 经 original 到 Counter.prototype,getter 接收 derived,检查私有字段时抛出 TypeError
属性查找沿原型链进行,私有字段检查发生在接收者自身

Counter.hasCount(derived) 把这次字段检查单独拿了出来。方法里的 #count in value 检查给定对象是否拥有这个类声明的私有字段。传 derived 得到 false,传非对象值会抛出 TypeError。

复制计数值时,重新创建实例

让计数器自己决定要复制哪些状态。这里的 copy() 先读出当前的 #count,再用 new Counter(this.#count) 初始化独立实例。把下面几行接到第一段代码后面,就能对比两份计数值。

const copy = original.copy();
copy.increment();

console.log(`has #count: ${Counter.hasCount(copy)}`);
console.log(`original.count: ${original.count}`);
console.log(`copy.count: ${copy.count}`);
控制台预期输出,副本拥有私有字段,原对象计数为 3,副本递增后为 4
第二段代码的预期控制台输出

副本递增后,原对象的计数仍是 3。这版 copy() 只带走计数值,公开字段 label 会按类定义初始化。以后加了新的状态,再按复制方法的约定决定哪些字段也要一起带走。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章