Core JavaScript 1.5 Reference:Operators:Special Operators:get Operator
From MDC
Contents |
[edit] Summary
Binds an object property to a function that will be called when that property is looked up.
[edit] Syntax
{get prop [ funname ]() { . . . } }
[edit] Parameters
-
prop - the name of the property to bind to the given function
-
funname - the (optional) name of the function to bind to the specified property
[edit] Description
Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want reflect the status of an internal variable without requiring the use of method calls, or a combination of the two. In JavaScript, this can be accomplished with the use of a getter. It is not possible to simultaneously have a getter on a property that holds an actual value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property.
A getter can be removed using the delete operator.
[edit] Examples
[edit] Example: Defining a getter with the get operator
This will create a pseudo-property latest of object o that will return the most recent entry into o.log:
var o = {
get latest () {
if (this.log.length > 0) {
return this.log[this.log.length - 1];
}
else {
return null;
}
},
log: []
}
Note that attempting to assign a value to latest will not change it.
[edit] Example: Deleting a getter using the delete operator
delete o.latest;