Our volunteers haven't translated this article into ไทย yet. Join us and help get the job done!
You can also read the article in English (US).
The get
syntax binds an object property to a function that will be called when that property is looked up.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Syntax
{get prop() { ... } } {get [expression]() { ... } }
Parameters
prop
- The name of the property to bind to the given function.
- expression
- Starting with ECMAScript 2015, you can also use expressions for a computed property name 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 to 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.
Note the following when working with the get
syntax:
- It can have an identifier which is either a number or a string;
- It 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);
- It 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 on new objects in object initializers
This will create a pseudo-property latest
for object obj
, which will return the last array item in log
.
var obj = { log: ['example','test'], get latest() { if (this.log.length == 0) return undefined; return this.log[this.log.length - 1]; } } console.log(obj.latest); // "test".
Note that attempting to assign a value to latest
will not change it.
Deleting a getter using the delete
operator
If you want to remove the getter, you can just delete
it:
delete obj.latest;
Defining a getter on existing objects using defineProperty
To append a getter to an existing object later at any time, use Object.defineProperty()
.
var o = {a: 0}; Object.defineProperty(o, 'b', { get: function() { return this.a + 1; } }); console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
Using a computed property name
var expr = 'foo'; var obj = { get [expr]() { return 'bar'; } }; console.log(obj.foo); // "bar"
Smart / self-overwriting / lazy getters
Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed, and if it is never needed, you never pay the cost.
An additional optimization technique to lazify or delay the calculation of a property value and cache it for later access are smart or memoized getters. The value is calculated the first time the getter is called and is then cached so subsequent accesses return the cached value without recalculating it. This is useful in the following situations:
- If the calculation of a property value is expensive (takes much RAM or CPU time, spawns worker thread, retrieves remote file, etc).
- If the value isn't needed just now. It will be used later, or in some case it's not used at all.
- If it's used, it will be accessed several times, and there is no need to re-calculate that value will never be changed or shouldn't be re-calculated.
This means that you shouldn't use a lazy getter for a property whose value you expect to change, because the getter will not recalculate the value.
In the following example, the object has a getter as its own property. On getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. Finally, the value gets returned.
get notifier() { delete this.notifier; return this.notifier = document.getElementById('bookmarked-notification-anchor'); },
For Firefox code, see also the XPCOMUtils.jsm code module, which defines the defineLazyGetter()
function.
get
Vs. defineProperty
While using the get
keyword and Object.defineProperty()
have similar results there is a subtle difference between the two when used on classes
.
When using get
the property will be defined on the prototype of the object while using Object.defineProperty()
the property will be defined on the instance it is applied to.
class Example { get hello() { return 'world'; } } const obj = new Example(); console.log(obj.hello); // "world" console.log(Object.getOwnPropertyDescriptor(obj, 'hello')); // undefined console.log(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), 'hello')); // { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined }
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 5.1 (ECMA-262) The definition of 'Object Initializer' in that specification. |
Standard | Initial definition. |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Method definitions' in that specification. |
Standard | Added computed property names. |
ECMAScript Latest Draft (ECMA-262) The definition of 'Method definitions' in that specification. |
Draft |
Browser compatibility
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Basic support | Chrome Full support 1 | Edge Full support Yes | Firefox Full support 2 | IE Full support 9 | Opera Full support 9.5 | Safari Full support 3 | WebView Android Full support 1 | Chrome Android Full support 18 | Edge Mobile Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes | nodejs Full support Yes |
Computed property names | Chrome Full support 46 | Edge Full support Yes | Firefox Full support 34 | IE No support No | Opera Full support 47 | Safari No support No | WebView Android Full support 46 | Chrome Android Full support 46 | Edge Mobile Full support Yes | Firefox Android Full support 34 | Opera Android Full support Yes | Safari iOS No support No | Samsung Internet Android Full support 5.0 | nodejs Full support Yes |
Legend
- Full support
- Full support
- No support
- No support
See also
- setter
delete
Object.defineProperty()
__defineGetter__
__defineSetter__
- Defining Getters and Setters in JavaScript Guide