Sub topic 1
Data Properties vs Accessor Properties
Prerequisites
This chapter assumes you know JavaScript objects and property access, functions and this, ES2015 class syntax, basic prototypes, and what strict mode does.
Two Kinds of Property
A data property stores a value. An accessor property stores no value. It holds a get function, a set function, or both, and JavaScript calls them when you read or assign the property. A property descriptor shows which kind you have:
| Kind | Descriptor keys |
|---|---|
| Data | `value`, `writable`, `enumerable`, `configurable` |
| Accessor | `get`, `set`, `enumerable`, `configurable` |
A descriptor cannot contain both value and get.
Your First Getter and Setter
In an object literal, put get or set in front of a method name:
const temperature = {
celsius: 20,
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
},
set fahrenheit(value) {
this.celsius = (value - 32) * 5 / 9;
}
};
temperature.fahrenheit = 212;
console.log(temperature.celsius); // 100
console.log(temperature.fahrenheit); // 212
const desc = Object.getOwnPropertyDescriptor(temperature, 'fahrenheit');
console.log(typeof desc.get, typeof desc.set); // 'function' 'function'
console.log('value' in desc); // falseOnly celsius is stored. fahrenheit is calculated each time you read it, so the two values always agree.
Accessors with Object.defineProperty
Object.defineProperty lets you set the descriptor flags yourself. If you leave out set, the property is read-only:
'use strict';
let balance = 0;
const account = {};
Object.defineProperty(account, 'balance', {
get() { return balance; },
enumerable: true,
configurable: false
});
console.log(account.balance); // 0
try {
account.balance = 50; // no setter defined
} catch (err) {
console.log(err instanceof TypeError); // true
}Getters and Setters in Classes
Class syntax works the same way. The accessor is defined once on the prototype, and every instance shares it:
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
}
const r = new Rectangle(3, 4);
console.log(r.area); // 12
console.log(Object.getOwnPropertyDescriptor(Rectangle.prototype, 'area').get !== undefined); // true
console.log(Object.keys(r)); // ['width', 'height']Because area lives on Rectangle.prototype, it does not appear in Object.keys(r).
Exercise
You call Object.getOwnPropertyDescriptor(obj, 'total') and get { get: [Function], set: undefined, enumerable: true, configurable: true }. What kind of property is total, and what happens when you run obj.total = 5 in strict mode?
Show answer
total is an accessor property because its descriptor has get and no value. It has no setter, so in strict mode the assignment throws a TypeError. Outside strict mode it would be silently ignored.