Class Accessors Compute On Read And Write
Class get/set accessors look like properties but run through the class: writes validate, reads derive, and read-only accessors reject assignment.
Code
// getter/setter 对外像属性,读写都经过类控制:赋值校验、读取派生
class Temperature {
#celsius = 0;
get celsius() {
return this.#celsius;
}
set celsius(value) {
if (typeof value !== 'number' || Number.isNaN(value)) {
throw new TypeError('celsius must be a number');
}
this.#celsius = value;
}
// 只读派生属性:没有 setter,严格模式下赋值直接抛错
get fahrenheit() {
return (this.#celsius * 9) / 5 + 32;
}
}
const temp = new Temperature();
temp.celsius = 25;
console.log('celsius:', temp.celsius, '| fahrenheit:', temp.fahrenheit);
temp.celsius = -40;
console.log('fahrenheit at -40C:', temp.fahrenheit);
try {
temp.celsius = 'not a number';
} catch (err) {
console.log('rejected:', err.message);
}
try {
temp.fahrenheit = 100;
} catch (err) {
console.log('read-only rejected:', err.name);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
celsius: 25 | fahrenheit: 77
fahrenheit at -40C: -40
rejected: celsius must be a number
read-only rejected: TypeErrorWhat the code does
Count the class Temperature as the entire surface area of Class Accessors Compute On Read And Write.
The failure path is explicit — TypeError is raised when the guard condition holds.
Module-level bindings hold the data — temp — with no function scope in between.
Applying it
Look for the celsius:, fahrenheit at -40C:, rejected: prefixes when the file runs; they tie each line to its step.
Statements that matter
throw new TypeError('celsius must be a number');
return (this.#celsius * 9) / 5 + 32;
return this.#celsius;
Interactive Tools for This Topic
FAQ
- What does the snippet do with malformed data?
- The code throws `TypeError`. Handle it at the call site or let it propagate deliberately.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `temp`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.