5
var a = {}; 

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

var i ="test";  

Is there any other way I can execute the getter besides 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');});

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.

0

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

OP seems to want to use the i variable. (while using var i to do it)
4

I guess closure compiler optimizes out the code because it doesn't actually do anything but access the properties. this should work:

module = {}; // global
for (var i in MyNameSpace){
    module = MyNameSpace[i];
}

Comments

0

Looking at your module example, seems like you just want a little refactoring there.

var moduleNames = { 'db', 'input', 'etc' };

for ( var name in moduleNames ) {
  MyNameSpace.__defineGetter__(name,function(){MyNameSpace.loadModule(name);});
}

function loadAll() {
  for ( var name in moduleNames ) {
    MyNameSpace.loadModule(name);
  }
}

If the functions themselves are less trivial than that, then you similarly want to collect the functions into a handy dictionary ahead of time, then loop over those to create the getter, and loop again to create the load all function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.