An accessor descriptor defines a property whose getter or setter runs when the property is read or assigned. Use Object.defineProperty to add one, or use getter and setter syntax in object literals and ES6 classes. section 9.1.2 section 9.5
Watch how the descriptor’s options and methods affect property behavior:
- A getter without a setter makes the property read-only; assigning to it throws in strict mode and fails silently otherwise. section 9.1.2
- A setter without a getter allows assignments, but reading the property returns undefined. section 9.1.2
- enumerable defaults to false; configurable also defaults to false, preventing redefinition or deletion. Set configurable to true to allow those changes. section 9.1.2
Object.defineProperty(ninjaCollection, "firstNinja", {
enumerable: true,
get() {
console.log(`Getting firstNinja: ${this.ninjas[0]}`);
return this.ninjas[0];
},
set(newNinja: string) {
console.log(`Setting firstNinja: ${newNinja}`);
this.ninjas[0] = newNinja;
},
});
This property makes firstNinja behave like a view of ninjas[0]: reading it calls the getter, and assigning to it calls the setter. section 9.1.2

