There are no true setters and getters in the commonly implemented Javascript versions, so if you want to emulate the effect you have to use some different syntax. For a property obj.x
, using obj.x()
to access the value of the property and obj.x(123)
to set the value seems like a rather convenient syntax.
It can be implemented like this:
// Basic property class
function Property(value) {
this.setter(value);
}
Property.prototype.setter = function(value) {
this.value = value * value;
}
Property.prototype.getter = function() {
return this.value;
}
Property.prototype.access = function(value) {
if (value !== undefined)
this.setter(value);
return this.getter();
}
// generator function to add convenient access syntax
function make_property(value) {
var prop = new Property(value);
function propaccess(value) {
return prop.access(value);
}
return propaccess;
}
Now properties generated by make_property
support the desired syntax and square values they are assigned:
var obj = {
x: make_property(2)
};
alert(obj.x()); // 4
obj.x(3); // set value
alert(obj.x()); // 9