Summary
Binds an object property to a function that will be called when that property is looked up.
Syntax
{get prop() { . . . } }
Parameters
-
prop
- the name of the property to bind to the given function
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 explicit method calls. In JavaScript, this can be accomplished with the use of a getter. It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property.
JavaScript 1.8.5 note
Starting in JavaScript 1.8.5, the get
operator:
- can have an identifier which is either a number or a string;
- must have exactly zero parameters (see Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments for more information);
- must not appear in an object literal with another
get
or with a data entry for the same property ({ get x() { }, get x() { } }
and{ x: ..., get x() { } }
are forbidden).
A getter can be removed using the delete
operator.
Examples
Defining a getter with the get
operator
This will create a pseudo-property latest
for object obj
, which will return the last array item in log
. Note: to append a getter to an existing object, use Object.defineProperty().
var log = ['test']; var obj = { get latest () { if (log.length == 0) return undefined; return log[log.length - 1] } } console.log (obj.latest); // Will return "test".
Note that attempting to assign a value to latest
will not change it.
Deleting a getter using the delete
operator
delete obj.latest;
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 5.1 (ECMA-262) The definition of 'get' in that specification. |
Standard | |
ECMAScript 6 (ECMA-262) The definition of 'get' in that specification. |
Draft |
Browser compatibility
Based on Robert Nyman's page
No support (notably in IE6-8) means that the script will trigger a syntax error.
Feature | Firefox (Gecko) | Chrome | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 2.0 (1.8.1) | 1 | 9 | 9.5 | 3 |
Feature | Firefox Mobile (Gecko) | Android | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
Basic support | ? | ? | ? | ? | ? |
See also
delete
set
Object.defineProperty()
__defineGetter__
__defineSetter__
- Defining Getters and Setters in JavaScript Guide