1

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

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

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

但就我而言,在运行时我得到一个字符串,我想将其插入到调用method函数 中

method现在,当我有以下字符串时,如何以编程方式访问

"app.property.method"       

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

4

3 回答 3

2

您需要使用括号表示法(我会避免使用其他选项 - eval())。如果app变量是全局变量,那么它将是window对象的属性:

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

借用方法:当我将其名称作为字符串时如何执行 JavaScript 函数

该方法本质上只是将您的window["app.property.method"](会失败的)分解为window["app"]["property"]["method"](有效的)。

于 2012-09-27T13:43:26.947 回答
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;
        };
    }
}());
于 2012-09-27T14:01:49.433 回答
0

你可以试试这个:

var methodString = "app.property.method";

var method = eval(methodString);

然后方法将是一个函数指针,可以这样调用:

method();
于 2012-09-27T13:43:36.990 回答