Search

12/29/2009

Javascript accessor properties

Javascript properties | accessors | getter / setter

Getter and setter functions are nice for data hiding, and even nicer when you can use them invisibly like plain data.

//they can be declared on an object literal
var o = {_name : "Start name",
writes : 0,
reads : 0,
name getter : function () {this.reads++; return this._name;},
name setter : function (n) {this.writes++; return this._name = n;}
}

//and can be added to extant objects
o.numwrites getter = function() { return this.writes;}
o.numwrites setter = function() {throw "no";}

//then use them
o.name ="adsfasdfadsF";
var foo = o.name;

innerHTML for Mozilla (WebFX)
Defining Getters and Setters
A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

var o = {
a:7,
get b() { return this.a + 1},
set c(x) {return this.a = x/2}
}
console.log(o.a); //7
console.log(o.b); //8
o.c = 50;
console.log(o.a); //25

Getters and setters can also be added to an object at any time after creation using two special methods called __defineGetter__ and __defineSetter__. Both methods expect the name of the getter or setter as their first parameter, in form of a string. The second parameter is the function to call as the getter or setter. For instance (following the previous example):

o.__defineGetter__("b", function() { return this.a+1; });
o.__defineSetter__("c", function(x) { this.a = x/2; });

Please note that function names of getters and setters defined in an object literal using "[gs]et property()" (as opposed to __define[GS]etter__ below) are not the names of the getters themselves, even though the [gs]et propertyName(){ } syntax may mislead you to think otherwise. To name a function in a getter or setter using the "[gs]et property()" syntax, put the name of the getter after the get or set and then put the function name after it. The following example shows how to name getter functions in object literals:

var objects = [{get a b(){return 1}},
{a getter:function b(){return 1}},
{"a" getter:function b(){return 1}}];

for (var i=0; i<objects.length; ++i)
print(objects[i].__lookupGetter__("a")) // prints "function b(){return 1}" for every getter.

沒有留言: