2012-09-27 62 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

相關問題