Javascript dynamic function calls with namespace

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?

Answers


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

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!


Need Your Help

Zend Framework 2 need PHP version 5.3.3?

php zend-framework2

They declare PHP_VERSION>=5.3.3, however, in its code, something like 'trait' which was introduced in 5.4 appear everywhere.I'm confused!

Spring Data MongoDB tries to generate queries for custom repository methods

java mongodb spring-data spring-data-document

Based on the Spring Data Document documentation, I have provided a custom implementation of a repository method. The custom method's name refers to a property which doesn't exist in the domain obje...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.