Take the following piece of javascript that is trying to implement a class:
function aClass(){
this.prop1 = this.getProp1();
}
aClass.prototype.getProp1 = function(){
// do some stuff
return result;
}
I can then use it like so:
var obj = new aClass();
alert(obj.prop1);
What I now want to do is this:
obj.prop1 = "some value";
This, of course overrides prop1, and I can no longer retrieve the generated result from the getProp1 function.
So in short, is it possible to create a property that allows read and write, but instead calls a function in both cases for, say, validation purposes?
I’m happy for a completely different approach to what I have here as long as I get the desired effect.
It needs to work with older browsers.
You can define getters and setters for object properties; see here and here. The syntax is going to be identical to getting or setting a property, but code will run instead of a dumb value change.
Live example.
Compatibility constraint: will not work in IE < 9.