2

Whereas using eval is not a good programming practice. This question is for didactic nature, or to learn a better solution:

See the following example in Javascript:

var foo = foo || {};
foo.bar = function(str) { alert(str); };

foo.bar('aaa'); // trigger alert('aaa')
window['foo']['bar']('bbb'); // trigger alert('bbb')

I'm searching for an generic caller to work with foo.bar('str'), foo.nestedObj.bar(params), foo.n2.n[1..99].bar(params)

Thats because I can't call something like:

param = [5,2,0];
call = 'foo.bar';
window[call](param); // not work

But I can call function using eval:

param = [5,2,0];
call = 'foo.bar'
eval(call + '(param)'); // works

How can I do this WITHOUT eval?

4

2 回答 2

5

我之前已经回答过这个问题,但这里又出现了:

function genericFunction(path) {

    return [window].concat(path.split('.')).reduce(function(prev, curr) {
        return prev[curr];
    });

}

var param = [5, 2, 0];
var foo = { bar: function(param) { return param.length; } };

genericFunction('foo.bar')(param);

// => 3
于 2013-01-23T11:55:53.817 回答
-1
callback = "foo.bar";
var p = callback.split('.'),
c = window; // "parent || window" not working in my tests of linked examples
for (var i in p) {
    if (c[p[i]]) {
        c = c[p[i]];
    } 
}
c('aaa');

这解决了问题。谢谢!

于 2013-01-23T12:11:52.350 回答