javascript property accessors

Jeff Storey picture Jeff Storey · Sep 7, 2012 · Viewed 12.6k times · Source

In Javascript, it seems like using property accessors is not all that common (unlike in other OO languages such as Java for example).

If I have a Person object with a name, defined as

function Person(name) {
   this.name = name;
}

A person's name is not going to change, but I do want to be able to access it when needed, so I could do something like:

function Person(name) {
   var name = name;
   this.getName = function() {
      return name;
   }
}

Even in a dynamic language, I think the principles of using getters and setters apply the same way they do to statically typed OO languages (e.g. encapsulation, adding validation, restricting access, etc)

This question may get closed as subjective, but I'm curious as to why this behavior doesn't appear more often (e.g. Java developers would go crazy if everything was public).

Is there a "standard" way to do this in javascript? I've seen Object.defineProperty, but not all browsers support that.

Answer

Matt Whipple picture Matt Whipple · Sep 7, 2012

Javascript has intercept-able property accessors:

http://ejohn.org/blog/javascript-getters-and-setters/

IMHO this is a far better solution to enforce the Uniform Access Principle than Java's more strict explicit getters, but that is also part of the simplicity and inflexibility of that language (Groovy for instance allows for similar interception).