Javascript defineGetter

var a = {}; 

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

var i ="test";  

Is there any other way that I can execute getter besides a[i](when using var ifor this)

EDIT:

I asked to use var ifor this purpose. I will explain the real problem a little better.

I use getters on my namespace object to load modules only when necessary.

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

In this case, I try to load all the modules:

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

I use the Google closure compiler for my code and reduce this loop above to:

for(var i in MyNameSpace);

No modules are loading. I am trying to trick gcc to load modules.

+5
source share
3 answers

a.test, a['test'] - test a , , getter.

: , , . , , - , , , JavaScript ( ECMAScript 5, ). Google Closure Tools, , , , JavaScript, . , .

, , , hasOwnProperty for-in.

+7

, , , . :

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

Looking at your example module, it 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, then you likewise want to pre-assemble the functions in a convenient dictionary, then loop them to create a getter and loop again to create the entire load function.

0
source

All Articles