How to dynamically access a variable in 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 area that I want to access using the variable name of the variable (for example, the name 'something' + someVar ). On a global scale, I just used window['varname'] , but obviously this does not work.

Is there a good way to do what I want? If I could not just put these variables inside an object to use array notation ...

Note: eval('varname') not an acceptable solution. Therefore, please do not offer this.

+4
source share
3 answers

This is a good question because this does not point to an anonymous function, otherwise you obviously just use this['something'+someVar] . Even using deprecated arguments.callee does not work here because internal variables are not properties of the function. I think you will need to do what you described by creating a holder object ...

 (function() { var holder = { something1: 'one', something2: 2, something3: 'three' }; for (var i = 1; i <= 3; i++) { console.log(holder['something'+i]); } })(); 
+8
source
 (function(globals) { /* do something */ globals[varname] = yourvar; })(yourglobals); 
+2
source

evil solution / hack: Put the variable you need into the obj helper object and you won’t have to change the current usage to dot notation using using (obj) {your current code ...}

+1
source

Source: https://habr.com/ru/post/1338549/


All Articles