Sub topic 4
Getters and Setters in Classes
This chapter assumes you know ES2015 class syntax, how this works inside methods, and the basics of the prototype chain. You have already seen get and set in object literals. Class syntax uses the same keywords. The difference is where the resulting property ends up.
The Syntax
Inside a class body, you write get or set before a method name. The getter takes no parameters. The setter takes exactly one.
class Person {
constructor(first, last) {
this.first = first;
this.last = last;
}
get fullName() {
return `${this.first} ${this.last}`;
}
set fullName(value) {
const [first, last] = value.split(' ');
this.first = first;
this.last = last;
}
}
const p = new Person('Ada', 'Lovelace');
console.log(p.fullName); // 'Ada Lovelace'
p.fullName = 'Grace Hopper';
console.log(p.first); // 'Grace'
console.log(p.last); // 'Hopper'Callers read and assign fullName like any other property. They never call it with parentheses.
Where the Accessor Lives
A class accessor is defined once, on Person.prototype. It is not copied onto each instance. When you read p.fullName, JavaScript finds no own property named fullName on p. It walks up to the prototype, finds an accessor there, and calls its get function with this set to p.
You can confirm this with the descriptor tools from the first chapter:
class Person {
constructor(first, last) {
this.first = first;
this.last = last;
}
get fullName() { return `${this.first} ${this.last}`; }
set fullName(value) { [this.first, this.last] = value.split(' '); }
}
const p = new Person('Ada', 'Lovelace');
console.log(Object.hasOwn(p, 'fullName')); // false
console.log(Object.keys(p)); // ['first', 'last']
const desc = Object.getOwnPropertyDescriptor(Person.prototype, 'fullName');
console.log(typeof desc.get, typeof desc.set); // 'function' 'function'
console.log(desc.enumerable); // falseClass accessors are non-enumerable. That is why Object.keys, for...in, and the spread operator skip them. Later chapters come back to what this means for serialization.
| Member | Defined on | Enumerable | Accessed as |
|---|---|---|---|
| Field or `this.x = ...` | Each instance | Yes | `obj.x` |
| Method | Prototype | No | `obj.m()` |
| Getter / setter | Prototype | No | `obj.x` / `obj.x = v` |
Getter-Only Properties and Strict Mode
If you define a getter with no setter, the property is read-only. What happens when someone assigns to it depends on the mode of the code doing the assignment. Class bodies always run in strict mode. Your own script may not.
class Circle {
constructor(radius) {
this.radius = radius;
}
get area() {
return Math.PI * this.radius ** 2;
}
resetArea() {
this.area = 0; // class code is strict: this throws
}
}
const c = new Circle(2);
c.area = 10; // sloppy script: silently ignored
console.log(c.area.toFixed(2)); // '12.57'
try {
c.resetArea();
} catch (err) {
console.log(err instanceof TypeError); // true
}Fields Shadow Accessors
Class fields are defined directly on each instance. If a field and an accessor share a name, the field creates an own data property, and lookup never reaches the accessor on the prototype. The setter is not called during field initialization either.
class Widget {
label = 'default';
get label() {
return 'from getter';
}
}
const w = new Widget();
console.log(w.label); // 'default'
console.log(Object.hasOwn(w, 'label')); // trueThis usually happens when you add a field to store the value behind an accessor and reuse the same name. Use a different name for the stored value. A common older convention is _label. The next chapter shows a better option: a private #label field that outside code cannot reach at all.
Exercise
You create 1,000 instances of Person. How many fullName accessor definitions exist, and what does Object.keys(new Person('A', 'B')) return?
Show answer
Only one. The accessor lives on Person.prototype and all instances share it. Object.keys returns ['first', 'last'], because the accessor is not an own property and class accessors are non-enumerable.
Exercise
A class declares a field count = 0; and also set count(v) { console.log('set', v); }. What does new Example().count = 5 log, and why?
Show answer
It logs nothing. The field creates an own data property named count on the instance, which shadows the setter on the prototype. The assignment updates that data property directly.