Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript infinite loop with defineSetter

Tags:

javascript


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?

like image 759
Yosi Avatar asked Jan 07 '11 08:01

Yosi


1 Answers

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

like image 184
Spiny Norman Avatar answered Sep 22 '22 00:09

Spiny Norman