用动态名称调用嵌套函数 [英] Call nested function with dynamic name

查看:55
本文介绍了用动态名称调用嵌套函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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

    b();
})();

此代码有效,但如果名称在字符串内(即动态),则在理论上可以调用 b()吗?

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

如果在全局范围内声明 b(),我们可以使用 window [stringContainingName](); .在这种情况下有可能吗?

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

这只是一个理论问题!我知道这样的代码设计不好.

推荐答案

此代码有效,但在理论上可以调用b()名称在字符串内(即动态)?

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).

如果在全局范围内声明b(),我们可以使用windowstringContainingName;在这种情况下有可能吗?

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()

...将两次记录'Works'.我在这里使用了显式的全局对象,就像在严格模式下直接声明给 b 而不声明它一样(使用 b = function()... 而不是 window.b = function()... )将导致ReferenceError.

... 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.

这篇关于用动态名称调用嵌套函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆