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?

Ragen Dazs
  • 2,115
  • 3
  • 28
  • 56

2 Answers2

5

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
Amberlamps
  • 39,180
  • 5
  • 43
  • 53
  • 1
    Please do not post duplicate answers. Just link to your previous post and cast a closevote. – georg Jan 23 '13 at 16:47
  • This is actually not a duplicate answer. I modified and improved this one. – Amberlamps Jan 23 '13 at 16:49
  • It might be a better option to edit the original one by improving it and providing a link. Also your answer doesn't provide any explanation. I would like to know why that function works. – jwize Jun 15 '14 at 10:27
-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');

And this solves the problem. Thanks!

Ragen Dazs
  • 2,115
  • 3
  • 28
  • 56