如何在匿名函数/闭包内动态访问变量? [英] How to access variable dynamically inside an anonymous function/closure?

查看:120
本文介绍了如何在匿名函数/闭包内动态访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了保持全局命名空间的清洁,我的JavaScript代码如下所示:

To keep the global namespace clean, my JavaScript code is wrapped like this:

(function() {
    /* my code */
})();

现在我有一些变量在这个范围内声明,我想使用变量变量名访问名称为'something'+ someVar )。
在全局范围我只需使用 window ['varname'] ,但显然不起作用。

Now I have some variables declared in this scope which I want to access using a variable variable name (e.g. the name is 'something' + someVar). In the global scope I'd simply use window['varname'], but obviously that doesn't work.

有什么好的方法来做我想要的吗?如果不是,我可以简单地把这些变量放在对象中使用数组符号...

Is there a good way to do what I want? If not I could simply put those variables inside an object to use the array notation...

注意: eval('varname')是不可接受的解决方案。

Note: eval('varname') is not an acceptable solution. So please don't suggest that.

推荐答案

这是一个很好的问题,因为 this 不指向匿名函数,否则你显然只需使用 this ['something'+ someVar] 。即使使用已弃用的 arguments.callee 在这里也不起作用,因为内部变量不是函数的属性。我想你必须做你所描述的,通过创建一个持有者对象...

This is a good question because this doesn't point to the anonymous function, otherwise you would obviously just use this['something'+someVar]. Even using the deprecated arguments.callee doesn't work here because the internal variables aren't properties of the function. I think you will have to do exactly what you described by creating either a holder object...

(function() {
  var holder = { something1: 'one', something2: 2, something3: 'three' };

  for (var i = 1; i <= 3; i++) {
    console.log(holder['something'+i]);
  }
})();

这篇关于如何在匿名函数/闭包内动态访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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