Calling javascript function with an objectstring in dot notation

前端 未结 3 1690
灰色年华
灰色年华 2021-02-20 17:14

Suppose I have the string:

var string = \"function\";

With

window[string];

I can call a function with the nam

3条回答
  •  生来不讨喜
    2021-02-20 17:46

    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.

提交回复
热议问题