javascript:闭包中的访问函数 [英] javascript: access function in closure

查看:30
本文介绍了javascript:闭包中的访问函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在变量中有一个函数的名称,但是所有内容都在一个闭包内.有了这个变量,我想调用函数,就像这样

I have the name of a function in a variable, but everything is within a closure. With this variable I want to call the function, something like this

(function(func) {
      this[func]() ;         // doesn't work

      function bar() {}
      function foo() {}
})('bar') ;

是否可能发生这种情况?例如,应该将函数添加到变量中,例如

Is something like this possible or should I, for example, add the functions to a variable, like

(function(func) {        
      var ns = {
          bar: function() {},
          foo: function() {}
      };

      ns[func]() ;         // OK
})('bar') ;

推荐答案

使用 [] 语法按名称无法访问在当前词法范围内声明的变量和函数-仅属性键(每秒)例如)可以根据另一个变量的内容动态查找.

Variables and functions declared in the current lexical scope cannot be accessed by name using [] syntax - only property keys (per your second example) can be looked up dynamically based on the contents of another variable.

解决此问题的唯一方法是求助于 eval ,这几乎从来不是一个好主意.

The only way around this is to resort to eval, which is almost never a good idea.

在全局范围内声明的变量和函数适用例外-它们实际上是 window 的属性.

An exception applies for variables and functions declared in the global scope - those are actually properties of window.

这篇关于javascript:闭包中的访问函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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