Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1074600 of getter

  • Revision slug: Web/JavaScript/Reference/Functions/get
  • Revision title: getter
  • Revision id: 1074600
  • Created:
  • Creator: mertenhanisch
  • Is current revision? No
  • Comment Fix typo

Revision Content

{{jsSidebar("Functions")}}

The get syntax binds an object property to a function that will be called when that property is looked up.

Syntax

{get prop() { ... } }
{get [expression]() { ... } }

Parameters

prop
The name of the property to bind to the given function.
expression
Starting with ECMAScript 6, 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:

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 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

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 {{jsxref("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

Note: Computed properties are experimental technology, part of the ECMAScript 6 proposal, and are not widely supported by browsers yet. This will trigger a syntax error in non-supporting environments.

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 it's own property. On getting the property, the property 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.

Specifications

Specification Status Comment
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}} {{Spec2('ES5.1')}} Initial definition.
{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}} {{Spec2('ES6')}} Added computed property names.
{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}} {{Spec2('ESDraft')}}  

Browser compatibility

{{CompatibilityTable}}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatChrome(1)}} {{ CompatGeckoDesktop("1.8.1") }} {{ CompatIE(9) }} 9.5 3
Computed property names {{CompatChrome(46)}} {{ CompatGeckoDesktop("34") }} {{CompatNo}} {{CompatNo}} {{CompatNo}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{ CompatGeckoMobile("1.8.1") }} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}
Computed property names 47 {{CompatNo}} {{ CompatGeckoMobile("34.0") }} {{CompatNo}} {{CompatNo}} {{CompatNo}}

See also

  • setter
  • {{jsxref("Operators/delete", "delete")}}
  • {{jsxref("Object.defineProperty()")}}
  • {{jsxref("Object.defineGetter", "__defineGetter__")}}
  • {{jsxref("Object.defineSetter", "__defineSetter__")}}
  • Defining Getters and Setters in JavaScript Guide

Revision Source

<div>{{jsSidebar("Functions")}}</div>

<p>The <strong><code>get</code></strong> syntax binds an object property to a function that will be called when that property is looked up.</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox">
{get <em>prop</em>() { ... } }
{get <em>[expression]</em>() { ... } }</pre>

<h3 id="Parameters">Parameters</h3>

<dl>
 <dt><code>prop</code></dt>
 <dd>The name of the property to bind to the given function.</dd>
 <dt>expression</dt>
 <dd>Starting with ECMAScript 6, you can also use expressions for a computed property name to bind to the given function.</dd>
</dl>

<h2 id="Description">Description</h2>

<p>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 <em>getter</em>. 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.</p>

<p>Note the following when working with the <code>get</code> syntax:</p>

<div>
<ul>
 <li>It can have an identifier which is either a number or a string;</li>
 <li>It must have exactly zero parameters (see <a class="external" href="https://whereswalden.com/2010/08/22/incompatible-es5-change-literal-getter-and-setter-functions-must-now-have-exactly-zero-or-one-arguments/" rel="external nofollow" target="_self">Incompatible <abbr title="ECMAScript 5th edition">ES5</abbr> change: literal getter and setter functions must now have exactly zero or one arguments</a> for more information);</li>
 <li>It must not appear in an object literal with another <code>get</code> or with a data entry for the same property (<code>{ get x() { }, get x() { } }</code> and <code>{ x: ..., get x() { } }</code> are forbidden).</li>
</ul>
</div>

<p>A getter can be removed using the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete" title="en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator">delete</a></code> operator.</p>

<h2 id="Examples">Examples</h2>

<h3 id="Defining_a_getter_on_new_objects_in_object_initializers">Defining a getter on new objects in object initializers</h3>

<p>This will create a pseudo-property <code>latest</code> for object <code>obj</code>, which will return the last array item in <code>log</code>.</p>

<pre class="brush: js">
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".
</pre>

<p>Note that attempting to assign a value to <code>latest</code> will not change it.</p>

<h3 id="Deleting_a_getter_using_the_delete_operator">Deleting a getter using the <code>delete</code> operator</h3>

<p>If you want to remove the getter, you can just <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code> it:</p>

<pre class="brush: js">
delete obj.latest;
</pre>

<h3 id="Defining_a_getter_on_existing_objects_using_defineProperty">Defining a getter on existing objects using <code>defineProperty</code></h3>

<p>To append a getter to an existing object later at any time, use {{jsxref("Object.defineProperty()")}}.</p>

<pre class="brush: js">
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)</pre>

<h3 id="Using_a_computed_property_name">Using a computed property name</h3>

<div class="note">
<p><strong>Note:</strong> Computed properties are experimental technology<em>,</em> part of the ECMAScript 6 proposal, and are not widely supported by browsers yet. This will trigger a syntax error in non-supporting environments.</p>
</div>

<pre class="brush: js">
var expr = "foo";

var obj = {
  get [expr]() { return "bar"; }
};

console.log(obj.foo); // "bar"</pre>

<h3 id="Smart_self-overwriting_lazy_getters">Smart / self-overwriting / lazy getters</h3>

<p>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.</p>

<p>An additional optimization technique to lazify or delay the calculation of a property value and cache it for later access are<strong> smart or <a href="https://en.wikipedia.org/wiki/Memoization">memoized</a> getters</strong>. 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&nbsp;is useful in the following situations:</p>

<ul>
 <li>If the calculation of a property value is expensive (takes much RAM or CPU time, spawns worker thread, retrieves remote file, etc).</li>
 <li>If the value isn't needed just now. It will be used later, or in some case it's not used at all.</li>
 <li>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.</li>
</ul>

<p>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.</p>

<p>In the following example, the object has a getter as it's own property. On getting the property, the property removed from the object and re-added, but implicitly as a data property this time. Finally the value gets returned.</p>

<pre class="brush: js">
get notifier() {
  delete this.notifier;
  return this.notifier = document.getElementById("bookmarked-notification-anchor");
},</pre>

<p>For Firefox code, see also the XPCOMUtils.jsm code module, which defines the <code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/XPCOMUtils.jsm#defineLazyGetter()">defineLazyGetter()</a></code> function.</p>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>Added computed property names.</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<p>{{CompatibilityTable}}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome(1)}}</td>
   <td>{{ CompatGeckoDesktop("1.8.1") }}</td>
   <td>{{ CompatIE(9) }}</td>
   <td>9.5</td>
   <td>3</td>
  </tr>
  <tr>
   <td>Computed property names</td>
   <td>{{CompatChrome(46)}}</td>
   <td>{{ CompatGeckoDesktop("34") }}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{ CompatGeckoMobile("1.8.1") }}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
  <tr>
   <td>Computed property names</td>
   <td>47</td>
   <td>{{CompatNo}}</td>
   <td>{{ CompatGeckoMobile("34.0") }}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a></li>
 <li>{{jsxref("Operators/delete", "delete")}}</li>
 <li>{{jsxref("Object.defineProperty()")}}</li>
 <li>{{jsxref("Object.defineGetter", "__defineGetter__")}}</li>
 <li>{{jsxref("Object.defineSetter", "__defineSetter__")}}</li>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Defining Getters and Setters</a> in JavaScript Guide</li>
</ul>
Revert to this revision