我想以编程方式访问嵌套在对象中的方法。
var app = {
property:{
method:function(){},
property:"foo"
}
}
通常您会像这样访问它:app.property.method
但在我的情况下,在运行时我得到一个字符串,我想插入它调用method
函数
现在,当我有以下字符串
时,如何以编程方式访问method
"app.property.method"
如需参考,请参阅: http://jsfiddle.net/adardesign/92AnA/
答案 0 :(得分: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"]
(可行)。
答案 1 :(得分: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 :(得分:0)
你可以试试这个:
var methodString = "app.property.method";
var method = eval(methodString);
然后方法将是一个函数指针,可以这样调用:
method();