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

随声附和 提交于 2019-12-01 06:58:57

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... }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!