views:

47

answers:

1
var a = {}; 

a.__defineGetter__('test',function() {return 5;}); 

var i ="test";  

Is there any other way I can execute the getter other than a[i]; (while using var i to do it)

EDIT:

I was asking ways to use var i to do it. I'll explain the real problem a bit better.

I am using getters on my namespace object to load modules only when needed.

MyNameSpace.__defineGetter__('db',function(){MyNameSpace.loadModule('db');});

Now in this case I am trying to load all modules:

for (var i in MyNameSpace){
    MyNameSpace[i];
}

I use google closure compiler on my code and it reduces that loop above to:

for(var i in MyNameSpace);

No modules get loaded. I am trying to "trick" gcc into letting me load the modules.

+3  A: 

You can do either a.test or a['test'] - both will access the test property of a and hence call the getter.

Edit: Ah, I see exactly what you want now. What you're doing is a clever use of getters, but unfortunately getters and setters aren't part of the current JavaScript standard (they are in ECMAScript 5 which isn't widely supported yet). Google Closure Tools seems to assume that reading a variable can't have any side-effect, which is true in the current versions of JavaScript, so I see no way to get around that. You'll have to edit the output to insert that stuff back.

Also, this isn't related to your question, but I do hope you're doing an additional hasOwnProperty check within the for-in construct.

casablanca
OP seems to want to use the `i` variable. *(while using var i to do it)*
patrick dw
+1 for `hasOwnProperty` suggestion.
Peter Ajtai