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

后端 未结 3 1702
甜味超标
甜味超标 2021-01-14 00:22

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

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

Now I have some variable

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-14 00:47

    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]);
      }
    })();
    

提交回复
热议问题