开发者

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

开发者 https://www.devze.com 2023-02-08 12:28 出处:网络
To keep the global namespace clean, my JavaScript code is wrapped like this: (function() { /* my code */

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 (e.g. the name is 'something' + someVar). In 开发者_StackOverflowthe 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);


evil solution/hack: Put the variable you need in a helper object obj and avoid having to change current uses to dot notation by using use with(obj){ your current code... }

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号