2011-08-09 76 views
1

我是JS对象的新手。我有这样的代码动态调用子对象的对象

var foo = { 
    bar0: { 
     barr0: function() {//doo stuff} 
     barr1: function() {//doo stuff} 
    }, 
    bar1: { 
     barr0: function() {//do stuff} 
     barr1: function() {//do stuff} 
    }, 
    bar2: function() {//do stuff} 
} 

现在我有这个变量myVar持有的任何格式以上,他们将被称为的“名称”。就像它可以有bar0.barr1bar2或提及其他任何上述对象一样。 foo将不会成为myVar的一部分,因为每次通话都很常见。一种可能的解决方案是使用eval,但如果可能的话,我想避免它。

如果对象是一维的,我会用foo[myVar](),但现在这是多维的,我不知道该怎么称呼它。

回答

2

然后您需要应用一些脚本。

// define our access string and copy a reference from foo into level 
var myVar = 'bar0.barr1', 
    level = foo; 

// split that access string into an Array (splitted by dots) and loop over it 
myVar.split(/\./).forEach(function(prop) { 
    // if the property name ("bar0", "barr1") is available in our target object 
    if(prop in level) { 
     // overwrite our level variable with the new object property reference, so somekind "climb up" the latter if we're dealing with nested objects 
     level = level[ prop ]; 
    } 
}); 

// if we're done, check if level holds a function reference and if so, execute it. 
if(typeof level === 'function') { 
    level(); 
} 
+0

请问您能否添加一些注释来描述上述代码的作用?我应该把它包装成一个函数?因为我将需要多次调用它.. – Achshar

+0

@Achshar:是的,完成。 – jAndy

+0

很酷..试着现在的代码..:D – Achshar