1

I looked at this:

Calling a JavaScript function named in a variable

But it doesn't answer my question.

This normally works:

window['class']['sub_class']['function_name'](data);

But now I'm trying to make a general function that can handle any depth:

function callbackFunction(callback, data){
    //callback = a.b.c, or a.b, or a
    callback = explode(callback);      

    //I need to be able to call callbackFunction and somehow callback and form their proper form below
    window[callback.a](data);
    //or
    window[callback.a][callback.b](data);
    //or
    window[callback.a][callback.b][callback.c](data);
}
4

2 回答 2

1

我相信 Bergi 建议的副本只能解决您一半的问题。由于您的最终值将是一个函数,并且由于该函数是对象的成员,因此您最终会在错误的上下文中执行它(即,使用错误的this值)。

我建议你使用这样的东西:

function getCallback(path) {
    var arr = path.split('.');
    var k;
    var fn = window;
    while(k = arr.shift()) {
        if(typeof fn[k] === "function") {
            fn = fn[k].bind(fn);
        } else {
            fn = fn[k]; 
        }
    }

    if(typeof fn === "function") return fn;
    return function(){};
}

http://jsfiddle.net/7CEd5/

this通过使用 Convert string in dot notation 的答案将回调中的值与您获得的值进行比较,以获取对象引用

于 2013-08-17T20:34:33.827 回答
0

您可以将对象/子对象/等的引用链接到您想要的任何时间。如果您有一个以点分隔的字符串(例如"document.blah.blah2.method"),那么您需要将其拆分为单独的标记(例如["document", "blah", "blah2", "method"])。

那么这只是一个循环遍历链的问题:

var c = window;
for (var i = 0; i < chain.length - 1; i++) {
  c = c[chain[i]];
}
c[chain[chain.length-1]](some_arguments);
于 2013-08-17T20:22:59.120 回答