I have the following the code -
var obj = {
name : "Yosy"
};
obj.__defineSetter__("name",function(v){
alert(v);
});
The problem is -
If I change obj.name to something else and console.log(obj) I will get undefined on the name property.
So I tried to fix obj.defineSetter to this -
var obj = {
name : "Yosy"
};
obj.__defineSetter__("name",function(v){
alert(v);
this.name = v;
});
If you the change name to "ABC" or something else you will get an infinite loop because in the defineSetter I am setting the value of the property "name".
what to do?
Well, if you want to be able to use the name
property like normal and still alert the value as well, you should name your object field differently, like this:
var obj = {
_name : "Yosy"
};
obj.__defineSetter__("name",function(v){
alert(v);
this._name = v;
});
obj.__defineGetter__("name",function() {
return this._name;
});
or something like this:
var obj = {
fields: {
name : "Yosy"
}
};
obj.__defineSetter__("name",function(v){
alert(v);
this.fields.name = v;
});
obj.__defineGetter__("name",function() {
return this.fields.name;
});
to prevent the setter from firing again when you set the property.
EDIT:
For anyone interested, here's some documentation: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Objects#Defining_Getters_and_Setters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With