Alex Rivera | Logout

Calling javascript function with an objectstring in dot notation

Asked 2011-07-11T03:51:19.443
10

Suppose I have the string:

var string = "function";

With

window[string];

I can call a function with the name of "function".

But, when I have:

var string2 = "function.method.weHaveTogoDeeper";

it should call

window["function"]["method"]["weHaveTogoDeeper"]

I can't do:

window[string2]

in this case. I dont know the number of "." in the string, so I need some kind of routine.

Edit
Report

1 Answer

1

I wrote one a while back:

function RecursiveMapper(handlerName, stack) {
    // check if empty string
    if(!handlerName || handlerName === '' || (handlerName.replace(/\s/g,'') === '')) return null;

    var buf = handlerName.split('.');
    stack = stack || window;
    return (buf.length === 1) ? stack[buf[0]] : this.RecursiveMapper(buf.slice(1).join('.'), stack[buf[0]]);
}

Call it like this: RecursiveMapper(window[string2]);

This one also checks if the function is defined in window scope first and returns the global one fi found.

answered 2011-07-11T03:59:23.930

Your Answer