December 2017
Beginner to intermediate
376 pages
7h 53m
English
To assign a value to a property of a JavaScript object is as simple as:
var myObj = { prop: 'Hello' }
To retrieve it is just as simple:
myObj.prop
There's no trick here. The point I want to make though, is that we can replace this normal assignment/retrieval mechanism of an object through use of getters and setters. These are special functions that allow custom logic for getting or setting the property's value.
Getters and setters are especially useful when one property's value is determined by another. Here's an example:
var person = { firstName: 'Abraham', lastName: 'Lincoln', get fullName() { return this.firstName + ' ' + this.lastName; }, set fullName(name) { var words = name.toString().split(' '); this.firstName ...
Read now
Unlock full access