Posted over 4 years ago. Visible to the public. Repeats.

Getter and setter functions for Javascript properties

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

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

Copy
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 ("()"):

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

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

However, you can define getters/setters using Object.defineProperty:

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

Some people are also doing some crazy things 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 dump property.

Alternatives for AngularJS

AngularJS has an alternative getter/setter pattern.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Henning Koch
Last edit:
about 2 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more