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:
function Test() {
var width = 100;
this.__defineGetter__("Width", function() {
return width;
});
this.__defineSetter__("Width", function(value){
width = value;
});
}
It looks like a plate of spaghetti ransacked by a kuri. What are some neater alternatives we have?
Note: The new code should access the value using new Test().Width
and not new Test().Width()
.
In Ecmascript5, the 'clean' (and standards compliant) way of doing this is with defineProperty.
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:
Here's a clean(er) alternative (also for older script engines):
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:
With ES5 you'll be able to do:
The getter/setter functions can of course do anything you want them to.