简体   繁体   English

如何在匿名函数/闭包中动态访问变量?

[英]How to access variable dynamically inside an anonymous function/closure?

To keep the global namespace clean, my JavaScript code is wrapped like this:为了保持全局命名空间干净,我的 JavaScript 代码是这样包装的:

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

Now I have some variables declared in this scope which I want to access using a variable variable name (eg the name is 'something' + someVar ).现在我在这个范围内声明了一些变量,我想使用变量变量名(例如,名称是'something' + someVar )访问它们。 In the global scope I'd simply use window['varname'] , but obviously that doesn't work.在全局范围内,我只是使用window['varname'] ,但显然这不起作用。

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...如果不是,我可以简单地将这些变量放在一个对象中以使用数组表示法......

Note: eval('varname') is not an acceptable solution.注意: eval('varname')不是可接受的解决方案。 So please don't suggest that.所以请不要建议。

This is a good question because this doesn't point to the anonymous function, otherwise you would obviously just use this['something'+someVar] .这是一个很好的问题,因为this并不指向匿名函数,否则您显然只会使用this['something'+someVar] Even using the deprecated arguments.callee doesn't work here because the internal variables aren't properties of the function.即使使用已弃用的arguments.callee在这里也不起作用,因为内部变量不是函数的属性。 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]);
  }
})();
(function(globals) {
    /* do something */
    globals[varname] = yourvar;
})(yourglobals);

邪恶的解决方案/黑客:将您需要的变量放在帮助对象obj 中,并避免通过使用 use with(obj){ your current code ... } 将当前用途更改为点表示法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM