开发者

Calling javascript function with an objectstring in dot notation

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"]["met开发者_如何转开发hod"]["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.


you can split the string across . by using the String.split method:

var string2 = "function.method.weHaveTogoDeeper";
var methods = string2.split(".");

In this examples, methods will be the array ["function","method","weHaveTogoDeeper"]. You should now be able to do a simple iteration over this array, calling each function on the result of the previous one.

Edit

The iteration I had in mind was something like this:

var result = window;
for(var i in methods) {
    result = result[methods[i]];
}

In your example, result should now hold the same output as

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


function index(x,i) {return x[i]}
string2.split('.').reduce(index, window);

edit: Of course if you are calling functions from strings of their names, you are likely doing something inelegant which would be frowned upon, especially in a collaborative coding settings. The only use case I can think of that is sane is writing a testing framework, though there are probably a few more cases. So please use caution when following this answer; one should instead use arrays, or ideally direct references.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜