Neat Alternatives To __definegetter__?
Getters and setters are a beauty in VB.Net: Get Return width End Get Set(ByVal value As Integer) width = value End Set In Javascript, this is probably what we would do: fu
Solution 1:
With ES5 you'll be able to do:
function Test() {
var a = 1;
return {
getA() { return a; },
setA(v) { a = v; }
};
}
The getter/setter functions can of course do anything you want them to.
Solution 2:
Here's a clean(er) alternative (also for older script engines):
functionTest() {
var a=1;
return { A: { toString: function(){return a;} } };
}
alert(Test().A); //=> 1
Mind you, you can't use it to define private/static complex structures. You can only 'get' strings or numbers (so immutable variables) with this pattern. Maybe the pattern can be enhanced using json.
[edit] Using json, you can also create a getter this way for objects:
functionTest() {
var a=1,
b = {foo:50, bar:100};
return {
A: { toString: function(){return a;} }
foobar: { toString: function(){returnJSON.stringify(b);} }
};
}
var foobar = JSON.parse(Test().foobar);
alert(foobar.foo); //=> 50
Solution 3:
In Ecmascript5, the 'clean' (and standards compliant) way of doing this is with defineProperty.
functionTest() {
var a = 1;
Object.defineProperty(this, "A", {get : function() {
return a;
},
enumerable : true});
}
This assumes that you just want to see how to define a getter. If all you want to do is make instances of Test immutable (a good thing to do where you can), you should use freeze for that:
functionTest() {
this.a = 1;
Object.freeze(this);
}
Post a Comment for "Neat Alternatives To __definegetter__?"