Accessor Properties
Description
Accessor properties do not contain a data value. They use a combination of a getter/setter function.
When an accessor property is read , the getter function is called. When an accessor property is written to, the setter function is called and acts on the new value.
Accessor properties have four attributes:
- Configurable - Indicates if the property may be redefined by removing the property via delete, changing the property's attributes, or changing the property into a data property. Default to true.
- Enumerable - Indicates if the property will be returned in a for-in loop. Default to true.
- Get - Marks the getter function. Default to undefined.
- Set - Marks setter function. The default value is undefined.
It is not possible to define an accessor property explicitly; you must use Object.defineProperty().
Example
var book = {
_year: 2004,/* w ww. j a v a2s .com*/
edition: 1
};
Object.defineProperty(book, "year", {
get: function(){
return this._year;
},
set: function(newValue){
if (newValue > 2004) {
this._year = newValue;
this.edition += newValue - 2004;
}
}
});
book.year = 2005;
console.log(book.year);
console.log(book.edition);
book.year = 2000;
console.log(book.year);
console.log(book.edition);
An object is created with two properties: _year and edition. The underscore on _year is a practice to indicate that a property is not intended to be accessed from outside of the object's methods.
The code above generates the following result.
Note
It's not necessary to assign both a getter and a setter.
A property with only getter method cannot be written to. In strict mode, trying to write to a property with only a getter throws an error.
A property with only a setter cannot be read and will return the value undefined in nonstrict mode, while doing so throws an error in strict mode.