get

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

Deleting a getter using the delete operator

delete o.latest;

Browser compatibility

Based on Robert Nyman's page

No support (notably in IE6-8) means that the script will trigger a syntax error.

  • Desktop
  • Mobile

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

Tags (3)

Edit tags

Attachments (0)

 

Attach file