Reputation: 2170
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
?
Upvotes: 2
Views: 1593
Reputation: 40488
I have answered this before, but here it goes again:
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
Upvotes: 5
Reputation: 2170
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');
And this solves the problem. Thanks!
Upvotes: -1