实现说明
除了类 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);