Sub topic 4
Getters and Setters in Classes
This chapter assumes you already know ES2015 class syntax, how this works inside methods, the basics of prototypes, and the descriptor model from the earlier chapters. In those chapters a descriptor with get and set functions marked an accessor property. Here you will see where class accessors are stored and how they behave when other code calls them. You will also meet a few traps that show up only in classes. Private fields, validation patterns, static accessors, and inheritance each get their own chapter later, so this one uses plain public properties as backing storage.
The Syntax
Inside a class body, you write get or set in front of a method name. The class then defines one accessor property with that name.
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) * 5 / 9;
}
}
const t = new Temperature(20);
console.log(t.fahrenheit); // 68
t.fahrenheit = 212;
console.log(t.celsius); // 100
console.log(t.fahrenheit); // 212The grammar has fixed rules:
| Rule | Getter | Setter |
|---|---|---|
| Parameters | Exactly zero | Exactly one (no rest parameter) |
| Return value | Becomes the result of the read | Ignored |
| Triggered by | `obj.name`, `obj[key]`, destructuring | `obj.name = v`, `obj[key] = v`, `+=`, `++` |
| Can be async or generator | No | No |
The setter's return value is always ignored. An assignment expression such as t.fahrenheit = 212 evaluates to 212, the right-hand side, whatever the setter returns. Compound operators run both halves: t.fahrenheit += 10 calls the getter, adds 10, and then calls the setter with the result.
Where Class Accessors Live
A class accessor is not copied onto each instance. It is defined once on the class's prototype object. Each instance finds it through the prototype chain. When the getter runs, this is the object the property was read from, so the getter sees that instance's data.
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
set fahrenheit(value) {
this.celsius = (value - 32) * 5 / 9;
}
}
const t = new Temperature(20);
console.log(Object.keys(t)); // [ 'celsius' ]
console.log(Object.hasOwn(t, 'fahrenheit')); // false
console.log('fahrenheit' in t); // true
const desc = Object.getOwnPropertyDescriptor(Temperature.prototype, 'fahrenheit');
console.log(typeof desc.get, typeof desc.set); // function function
console.log(desc.enumerable, desc.configurable); // false true
for (const key in t) console.log(key); // celsius
console.log(JSON.stringify(t)); // {"celsius":20}Class accessors and object-literal accessors differ in one attribute:
| Defined in | Stored on | enumerable | configurable |
|---|---|---|---|
| Object literal `{ get x() {} }` | The object itself | `true` | `true` |
| Class body `get x() {}` | `Class.prototype` | `false` | `true` |
| `Object.defineProperty` (defaults) | Target object | `false` | `false` |
Because class accessors are non-enumerable and live on the prototype, they stay out of Object.keys, for...in, object spread, Object.assign, and JSON.stringify. This is the most common surprise. Callers can read t.fahrenheit, but { ...t } does not contain it. A later chapter covers serialization in detail. For now, remember that an accessor behaves like a property when read but is not copied with the instance's data.
Getter-Only and Setter-Only Accessors
You can define only one half of an accessor. A getter with no setter gives you a read-only computed property:
class Circle {
constructor(radius) {
this.radius = radius;
}
get area() {
return Math.PI * this.radius ** 2;
}
}
const c = new Circle(2);
console.log(c.area.toFixed(2)); // 12.57
function assignStrict(obj) {
'use strict';
obj.area = 100;
}
try {
assignStrict(c);
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(c.area.toFixed(2)); // 12.57Class bodies always run in strict mode, but that rule covers only code inside the class. Whether assigning to a getter-only property throws depends on the mode of the code that does the assignment. In a sloppy-mode script, such as a CommonJS file run with node, c.area = 100 fails silently. In an ES module, or anywhere with 'use strict', it throws a TypeError. The example puts the directive inside assignStrict, so it behaves the same in both environments.
A setter with no getter is legal, but reading the property returns undefined. This is rarely what you want. Use it only for write-only inputs, such as a password property that hashes its value and never exposes it.
Constructors Go Through Setters
Inside the constructor, this.fahrenheit = value is an ordinary assignment. The lookup finds the prototype setter and calls it. Every value assigned in the constructor therefore gets the same handling as later assignments, which is why the validation chapter routes constructor input through setters.
The getter and setter usually need somewhere to keep the real value. It cannot have the same name as the accessor (the pitfalls chapter shows the infinite recursion this causes). Until private fields are introduced in the next chapter, this one uses a separately named public property:
class Product {
constructor(name, price) {
this.name = name;
this.price = price; // calls the setter
}
get price() {
return this.priceInCents / 100;
}
set price(value) {
this.priceInCents = Math.round(value * 100);
}
}
const p = new Product('Pen', 1.239);
console.log(p.price); // 1.24
console.log(p.priceInCents); // 124The obvious weakness is that anyone can write p.priceInCents directly. Private fields fix that.
The Class Field Trap
Public class field declarations (name = value; in the class body) do not use assignment. They define an own data property on each instance with [[DefineOwnProperty]] semantics. If a field has the same name as an accessor, the field shadows the accessor, and the setter never runs.
class Profile {
name = 'anonymous'; // defines an own data property
get name() {
return this.storedName;
}
set name(value) {
console.log('setter ran');
this.storedName = value;
}
}
const profile = new Profile(); // nothing is logged
console.log(Object.hasOwn(profile, 'name')); // true
profile.name = 'Ada'; // writes the own data property
console.log(profile.name); // Ada
console.log(profile.storedName); // undefinedTo fix this, remove the field and do the assignment in the constructor (this.name = 'anonymous'), or give the backing storage a different name. TypeScript users can hit this when they redeclare a property in a subclass. With useDefineForClassFields turned on (the default for ES2022 and later targets), the redeclaration shadows the parent's accessor in the same way.
Computed and Symbol Names
Accessor names can be computed expressions in square brackets, including symbols. This lets a class plug into built-in protocols:
const labelKey = 'label';
class Tag {
constructor(text) {
this.text = text;
}
get [labelKey]() {
return `#${this.text}`;
}
get [Symbol.toStringTag]() {
return 'Tag';
}
}
const tag = new Tag('js');
console.log(tag.label); // #js
console.log(Object.prototype.toString.call(tag)); // [object Tag]Caching an Expensive Getter
A getter runs on every read. If the computation is expensive and the inputs never change, the getter can replace itself on first use. It does this by defining an own data property on the instance, which then shadows the prototype accessor on every later read:
class Report {
constructor(rows) {
this.rows = rows;
}
get total() {
console.log('computing');
const value = this.rows.reduce((sum, n) => sum + n, 0);
Object.defineProperty(this, 'total', {
value,
writable: false,
enumerable: false,
configurable: true
});
return value;
}
}
const r = new Report([1, 2, 3]);
console.log(r.total); // logs 'computing', then 6
console.log(r.total); // 6 (no recomputation)
r.rows.push(4);
console.log(r.total); // still 6: the cache is staleThe last line shows the trade-off. Lazy caching is safe only when the inputs are immutable. Otherwise you need explicit invalidation.
`this` and Detached Accessors
Destructuring calls the getter on the source object, so const { fahrenheit } = t works. If you pull the getter function out of its descriptor, though, it no longer has a receiver:
class Temperature {
constructor(celsius) { this.celsius = celsius; }
get fahrenheit() { return this.celsius * 9 / 5 + 32; }
}
const t = new Temperature(0);
const { fahrenheit } = t;
console.log(fahrenheit); // 32
const getter = Object.getOwnPropertyDescriptor(Temperature.prototype, 'fahrenheit').get;
console.log(getter.call(t)); // 32
try {
getter(); // this is undefined in strict class code
} catch (err) {
console.log(err instanceof TypeError); // true
}Accessor or Method?
| Use a getter when | Use a method when |
|---|---|
| The value is cheap and quick to compute | The work is slow, does I/O, or is async |
| Reading has no side effects | The call changes state or has effects |
| Repeated reads give the same result | The result varies between calls (e.g. random, time) |
| No arguments are needed | Arguments are needed |
Callers expect obj.x to behave like a field. A getter that performs a network request or changes state breaks that expectation, and it also makes debugger output and logging misleading. Many debuggers evaluate getters when you hover over or expand an object.
Exercise
Given class Box { size = 1; get size() { return 99; } }, what does new Box().size print, and what does Object.keys(new Box()) return? Explain why.
Show answer
It prints 1, and Object.keys returns ['size']. The field declaration defines an own, enumerable data property named size on each instance. That property shadows the non-enumerable getter on Box.prototype, so the getter never runs.
Exercise
Write a class Rectangle with width and height data properties and a getter-only area. Then explain what happens when sloppy-mode code runs rect.area = 50, and what happens when an ES module runs the same line.
Show answer
class Rectangle { constructor(w, h) { this.width = w; this.height = h; } get area() { return this.width this.height; } }. In sloppy mode the assignment is silently ignored and area keeps returning width height. In an ES module, which is always strict, the assignment throws a TypeError because the accessor has no setter. Strictness is decided by the code doing the assignment, not by the class body.
Exercise
Why does JSON.stringify(new Temperature(20)) produce {"celsius":20} without a fahrenheit key, even though t.fahrenheit returns 68?
Show answer
JSON.stringify serializes only own enumerable string-keyed properties. The fahrenheit accessor is defined on Temperature.prototype, not on the instance, and class accessors are non-enumerable. Only the own data property celsius is included.