get Redirect 1

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:

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;

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

 

Document Tags and Contributors

Last updated by: Sheppy,