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

少し前に、パスを説明する文字列からオブジェクトを取得するために、この小さなスクリプトを作成しました。

(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 に答える
2

角かっこ表記を使用する必要があります(他のオプションは避けます- eval())。変数がグローバルの場合app、それはwindowオブジェクトのプロパティになります。

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

借用したメソッド:名前が文字列の場合にJavaScript関数を実行する方法

このメソッドは、基本的に、window["app.property.method"](失敗する)をwindow["app"]["property"]["method"](機能する)に分割するだけです。

于 2012-09-27T13:43:26.947 に答える
0

あなたはこれを試すことができます:

var methodString = "app.property.method";

var method = eval(methodString);

その場合、メソッドは次のように呼び出される関数ポインタになります。

method();
于 2012-09-27T13:43:36.990 に答える