我想以编程方式访问嵌套在对象中的方法。
var app = {
property:{
method:function(){},
property:"foo"
}
}
通常你会像这样访问它:app.property.method
但在我的例子中,在运行时我得到一个字符串,我想将其插入到调用 method
函数中
现在,当我有以下字符串时,如何以编程方式访问 method
"app.property.method"
有关引用,请参阅: http://jsfiddle.net/adardesign/92AnA/
最佳答案
前一段时间我写了这个小脚本来从描述其路径的字符串中获取一个对象:
(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;
};
}
}());
关于javascript - 通过字符串到达嵌套方法的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12622770/