← 中文资源

简体中文版本

类字段是定义而不是赋值

ES2022 类字段按 define 语义创建自有属性:子类用字段重声明基类访问器会被 TS2610 拒绝。想写入就走构造函数或方法里的赋值,赋值命中的才是原型上的 setter。

阅读英文原文

运行结果

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

setter ran: 21.5
setter ran: 30
final read: 30

实现说明

除了类 Temperature、Warm,文件里再无其他定义。 warm 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 跑完文件,输出里会留下标记——setter ran:、final read:。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。 跨调用保留的状态放在这些顶层绑定里:warm。

核心语句

return this.#celsius;

代码示例

class Temperature {
  #celsius = 0;

  get celsius(): number {
    return this.#celsius;
  }

  set celsius(value: number) {
    console.log('setter ran:', value);
    this.#celsius = value;
  }
}

// Field declarations use define semantics: they create own properties.
// Plain JavaScript would let a subclass field silently shadow the base
// accessor, so TypeScript refuses it at compile time instead:
// class Snapshot extends Temperature {
//   celsius = 21.5; // TS2610: accessor overridden as an instance property
// }

// To write through the base setter, assign — never re-declare a field.
// Assignments in constructors and methods hit the accessor on the prototype.
class Warm extends Temperature {
  constructor() {
    super();
    this.celsius = 21.5;
  }
}

const warm = new Warm();
warm.celsius = 30;
console.log('final read:', warm.celsius);