Call nested function with dynamic name

不打扰是莪最后的温柔 提交于 2021-02-05 09:27:17

问题


Consider this code:

(function a() {
    // Nested function
    function b() {
        console.log("Works!");
    }

    b();
})();

This code works, but would it be possible (in theory) to call b() if the name is inside a string (i.e. dynamic)?

If b() would be declared in the global scope, we could use window[stringContainingName]();. Is there a possibility in this case?

This is only a theoretical question! I know that such code is bad design.


回答1:


This code works, but would it be possible (in theory) to call b() if the name is inside a string (i.e. dynamic)?

No, function declaration has the same rules for scope, so it's not possible even in theory (unless we talk about closures, of course).

If b() would be declared in the global scope, we could use windowstringContainingName; Is there a possibility in this case?

Yes, of course: this...

(function a() {
    // Nested function
    window.b = function() {
        console.log("Works!");
    }
    b();
})();
b(); // or window['b'](), or window.b()

... will log 'Works' twice. I used explicit global object here, as in the strict mode direct assignment to b without declaring it (using b = function() ... instead of window.b = function() ...) will cause ReferenceError.




回答2:


Is there a possibility in this case?

Only by making the b function a property of an object:

(function a(name) {
    var fns = {
        b: function b() {
            console.log("Works!");
        }
    };

    // possibly secure by `if (fns.hasOwnProperty(name))`
    fns[name]();
})("b");

You will need to know the names of the functions in beforehand.



来源:https://stackoverflow.com/questions/18764657/call-nested-function-with-dynamic-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!