javascript - 通过字符串到达​​嵌套方法的最佳方法

标签 javascript dynamic interpolation

我想以编程方式访问嵌套在对象中的方法。

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/

相关文章:

javascript - 计算年龄(以天为单位) - Javascript

javascript - IE6 Try/Catch block 不适用于自定义 document.someFunction 调用

javascript - JQuery 升序和降序排序(不是表格)

c# - 在 C# Web 应用程序而不是网站中动态加载用户控件

python - 将强度附加到 3D 图

python - 样条滤波和样条插值有什么区别?

c++ - 使用 C++ 和 RGBA 像素 vector 的双线性调整大小

javascript - jQuery outerHTML 关闭标记

javascript - 如何隐藏粒子效果(圆圈)直到加载其动画的 .png?

java - 使用java反射调用spring bean