4

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

4
  • Could you say more specifically what it is you want to do when you want to "access them dynamically"? Do you want to access them outside the function? That's not possible AFAIK. Commented Feb 5, 2011 at 13:50
  • No, i just want to access them without hardcoding the variable name - but from inside my function. Commented Feb 5, 2011 at 13:51
  • "Dynamically" - what scope do you mean? Commented Feb 5, 2011 at 13:54
  • With "dynamically" i mean with a dynamically generated variable name. Commented Feb 5, 2011 at 13:56

3 Answers 3

8

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]);
  }
})();
Sign up to request clarification or add additional context in comments.

Comments

2
(function(globals) {
    /* do something */
    globals[varname] = yourvar;
})(yourglobals);

3 Comments

"To keep the global namespace clean" - so obviously I do not want to add it to the global namespace.
@ThiefMaster: globals doesn't necessarily mean global namespace -- it's just a parameter here and could very well be your own namespace. This doesn't deserve a -1.
The initial answer only suggested window[varname] = yourvar;
1

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

1 Comment

it should be avoided... it's a bit slower

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.