Posted over 6 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:

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 doesn't support getter/setter functions, and probably never will.

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

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

Alternatives for AngularJS

AngularJS has an alternative getter/setter pattern.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Henning Koch
Last edit:
4 months 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 short-lived cookies to improve usability.
Accept or learn more