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:

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

Alternatives for AngularJS

AngularJS has an alternative getter/setter pattern.

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Henning Koch
Last edit:
over 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