JavaScript objects can have getter and setter functions that are called when a property is read from or written to.
For example, if you'd like an object that has a virtual person.fullName
attribute that dynamically composes person.firstName
and person.lastName
:
var person = {
firstName: 'Guybrush',
lastName: 'Threepwood',
get fullName() {
return this.firstName + " " + this.lastName;
},
set fullName(name) {
var parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
};
The code below shows how this object can be used. Notice the absence of parentheses ("()
"):
person.fullName = 'Anna Pearson';
person.firstName; // => "Anna"
person.lastName; // => "Pearson"
person.firstName = 'Nick';
person.fullName; // => "Nick Pearson"
If you'd like to define getters and setters on an existing object, use Object.defineProperty()
instead:
var person = {
firstName: 'Guybrush',
lastName: 'Threepwood'
};
Object.defineProperty(person, "fullName", {
get: function() {
return this.firstName + " " + this.lastName;
},
set: function(name) {
var parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
});
Browser compatibility
Works with IE9+ and real browsers.
CoffeeScript
CoffeeScript doesn't support getter/setter functions, and probably never will Show archive.org snapshot .
However, you can define getters/setters using
Object.defineProperty
Show archive.org snapshot
:
object = {}
fooValue = undefined
Object.defineProperty object, 'foo',
get: -> fooValue
set: (newValue) -> fooValue = newValue
Some people are also doing some
crazy things
Show archive.org snapshot
to allow easier definition of getters/setters in class
definitions.
Performance considerations
Read and write accesses have the same performance characteristics of regular function calls, so it's slower than a dumb property.