Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript property accessors

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.

like image 979
Jeff Storey Avatar asked Sep 07 '12 21:09

Jeff Storey


1 Answers

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

like image 146
Matt Whipple Avatar answered Oct 19 '22 22:10

Matt Whipple