简体   繁体   中英

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

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

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

Note: eval('varname') is not an acceptable solution. 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] . 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]);
  }
})();
(function(globals) {
    /* do something */
    globals[varname] = yourvar;
})(yourglobals);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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