Read more

Getter and setter functions for JavaScript properties

Henning Koch
January 13, 2015Software engineer at makandra GmbH

JavaScript objects can have getter and setter functions that are called when a property is read from or written to.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

For example, if you'd like an object that has a virtual person.fullName attribute that dynamically composes person.firstName and person.lastName:

var person = {

  firstName: 'Guybrush',

  lastName: 'Threepwood',

  get fullName() {
    return this.firstName + " " + this.lastName;
  },
  
  set fullName(name) {
    var parts = name.split(" ");
    this.firstName = parts[0];
    this.lastName = parts[1];
  }

};

The code below shows how this object can be used. Notice the absence of parentheses ("()"):

person.fullName = 'Anna Pearson';
person.firstName; // => "Anna"
person.lastName; // => "Pearson"
person.firstName = 'Nick';
person.fullName; // => "Nick Pearson"

If you'd like to define getters and setters on an existing object, use Object.defineProperty() instead:

var person = {
  firstName: 'Guybrush',
  lastName: 'Threepwood'
};

Object.defineProperty(person, "fullName", {
  get: function() {
    return this.firstName + " " + this.lastName;
  },
  set: function(name) {
    var parts = name.split(" ");
    this.firstName = parts[0];
    this.lastName = parts[1];
  }
});

Browser compatibility

Works with IE9+ and real browsers.

CoffeeScript

CoffeeScript doesn't support getter/setter functions, and probably never will Show archive.org snapshot .

However, you can define getters/setters using Object.defineProperty Show archive.org snapshot :

object = {}

fooValue = undefined

Object.defineProperty object, 'foo', 
  get: -> fooValue
  set: (newValue) -> fooValue = newValue

Some people are also doing some crazy things Show archive.org snapshot to allow easier definition of getters/setters in class definitions.

Performance considerations

Read and write accesses have the same performance characteristics of regular function calls, so it's slower than a dumb property.

Henning Koch
January 13, 2015Software engineer at makandra GmbH
Posted by Henning Koch to makandra dev (2015-01-13 18:55)