2012-09-27 65 views
1

我想以编程方式达到嵌套在对象内部的方法。通过字符串达到嵌套方法的最佳方法

var app = { 
    property:{ 
     method:function(){}, 
     property:"foo" 
    }  
} 

通常你会访问它像这样:app.property.method

但在我的情况下,在运行时,我感到我想插即到调用method功能

现在一个字符串,怎么能method通过编程方式访问时,我有以下字符串

"app.property.method"  

参考请看: http://jsfiddle.net/adardesign/92AnA/

回答

2

前一段时间我写了这个小脚本来得到一个对象描述其路径的字符串:

(function() { 
    "use strict"; 
    if (!Object.fromPath) { 
     Object.fromPath = function (context, path) { 
      var result, 
       keys, 
       i; 
      //if called as `Object.fromPath('foo.bar.baz')`, 
      //assume `window` as context 
      if (arguments.length < 2) { 
       path = context; 
       context = window; 
      } 
      //start at the `context` object 
      result = context; 
      //break the path on `.` characters 
      keys = String(path).split('.'); 
      //`!= null` is being used to break out of the loop 
      //if `null` or `undefined are found 
      for (i = 0; i < keys.length && result != null; i+= 1) { 
       //iterate down the path, getting the next part 
       //of the path each iteration 
       result = result[keys[i]]; 
      } 
      //return the object as described by the path, 
      //or null or undefined if they occur anywhere in the path 
      return result; 
     }; 
    } 
}()); 
2

你需要使用括号符号(我会避免其他选项 - eval())。如果app变量是全球性的,那么这将是window对象的属性:从借来的

executeFunctionByName("app.property.method", window); 

方法:How to execute a JavaScript function when I have its name as a string

的方法本质上只是伤了你的window["app.property.method"](这将失败)为window["app"]["property"]["method"](其中作品)。

+0

这正是我一直在寻找的,我想推出我自己的解决方案,谢谢。 – adardesign

0

你可以试试这个:

var methodString = "app.property.method"; 

var method = eval(methodString); 

则方法将是一个函数指针可以被称为像这样:

method(); 
+0

谢谢,是的,我试图避免评估。不管怎样,谢谢! – adardesign

相关问题