Sub topic 2
Declaring Public Instance Fields
This chapter assumes you can write a class with a constructor and methods, and that you know how this normally works. It adds the members that give a class its state: public and private fields, accessors, and static members. It ends with the most common class bug, a lost this.
Fields, Accessors, Static and Private Members
A public field declares a property directly in the class body. Each instance gets its own copy before the constructor body runs. A getter (get) or setter (set) looks like a property to the caller but runs a function. Static members belong to the class itself, not to its instances. A static block runs once, when the class is defined. A private name begins with # and is visible only inside the class body.
class Temperature {
static instances = 0;
static units;
static {
Temperature.units = Object.freeze(['C', 'F']);
}
unit = 'C'; // public field
#celsius = 0; // private field
constructor(celsius) {
this.#celsius = celsius;
Temperature.instances++;
}
get fahrenheit() {
return this.#celsius * 9 / 5 + 32;
}
set fahrenheit(f) {
this.#celsius = (f - 32) * 5 / 9;
}
#round(n) {
return Math.round(n * 10) / 10;
}
describe() {
return `${this.#round(this.#celsius)}°${this.unit}`;
}
static isTemperature(obj) {
return #celsius in obj;
}
}
const t = new Temperature(20);
console.log(t.fahrenheit); // 68
t.fahrenheit = 212;
console.log(t.describe()); // '100°C'
console.log(Temperature.instances); // 1
console.log(Temperature.units); // [ 'C', 'F' ]
console.log(Temperature.isTemperature(t)); // true
console.log(Temperature.isTemperature({}));// false| Common error | Cause |
|---|---|
| `t.instances` is `undefined` | Static members live on the class, so use `Temperature.instances` |
| `SyntaxError` on `t.#celsius` outside the class | Private names cannot be reached from outside the class body |
| Infinite recursion in a setter | The setter assigns to its own property name, so store the value in `#field` |
Keeping this Bound When Methods Become Callbacks
Class bodies run in strict mode. A method that is detached from its instance gets this === undefined. An arrow function stored in a field captures the instance when the instance is created, so it stays bound.
class Button {
label = 'OK';
handleClick = () => this.label;
describe() {
return this.label;
}
}
const btn = new Button();
const { handleClick, describe } = btn;
console.log(handleClick()); // 'OK'
console.log(describe.bind(btn)()); // 'OK'
try {
describe();
} catch (e) {
console.log(e instanceof TypeError); // true
}Exercise
Why does setTimeout(timer.tick, 1000) fail inside tick with a TypeError when tick is an ordinary method that reads this.#count, and what are two ways to fix it?
Show answer
setTimeout calls the detached function without a receiver, and strict mode leaves this as undefined, so reading #count from it throws. One fix is to pass () => timer.tick() or timer.tick.bind(timer). The other is to declare tick as an arrow-function field, tick = () => { ... }.