开发者

How to define getters and setters in a loop?

I want to define setters and getters in the following way:

var myObj = {
    // this is the o开发者_StackOverflowbject that should be 
    // filled with new setters and getters
    ...
}
/**
* This object contains getters and setters for myObj
*/
var Fields = {
   param1: {defaultValue: ..., type: ..., ...}
   param2: ...
}
// so the following code doesn't work properly
for (var field in Fields)
    Object.__defineGetter__(field, function() {
        // do smth
    });

this code leads to that all the getters are doing the same stuff (corresponding to the last iteration of the for loop)

How should I modify the code to make it work properly?


Wrap the body of the for loop in an anonymous function, in this way:

for (var field in Fields){
    (function(field){
        myObj.__defineGetter__(field, function() {
            // do something, pointing to unique variables using "field"
            // Example:
            doSomethingSpecial(Fields[field].defaultValue);
        });
    })(field)
}

This method's effect is based on the fact that (anonymous) functions have an own scope. The primitive variables (strings, numbers) are passed by value as an argument to the function. Because of this, the field property inside the anonymous function is distinct from the field property, defined in the loop.
When the value of field (outside the function) is changed, the field variable inside the function does not change.

I have also replaced Object bymyObj. If that's incorrect, revert the change.


This feature is only avaliable in Firefox.

In this link http://www.codeproject.com/KB/scripting/crossbrowserjavascript.aspx shows that.

"The defineGetter and defineSetter are unique features to Mozilla/FireFox and you can find some (still few) samples on the internet by searching through Google for these keywords."


var properties=['asd','asd2','asd3'];

var myob = function(){};

for(var x=0;x<properties.length;x++)
{
    var p = properties[x];

    var getter = function(){ return this['_' + arguments.callee.propname]; };
    getter.propname = p;
    myob.prototype.__defineGetter__(p, getter);


    var setter = function(value){ this['_' + arguments.callee.propname] = value; };
    setter.propname = p;
    myob.prototype.__defineSetter__(p, setter);
}


var myobi = new myob();

myobi.asd = 33;
alert(myobi._asd);
alert(myobi.asd);
myobi.asd2 = 44;
alert(myobi._asd2);
alert(myobi.asd2);

HTH!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜