3

How should I create a changing variable as a global variable?

so something like:

function globVar(variable){
   window.variable;
}

So in this way I could create global variables in an automatic mode too, and also I could create them for myself easier :)

EDIT

For example I could create a global variable just like this: globVar('myVariable'); then myVariable is added to the global variables.

3
  • "Global variables" are (white lie) "window attributes" (in browser contexts). What do you mean? Commented Nov 13, 2010 at 17:42
  • What is myVariable supposed to equal when you call globVar('myVariable')? Commented Nov 13, 2010 at 17:47
  • @Lime - Well doesn't really matter, but as default should be null. :) Commented Nov 13, 2010 at 17:48

3 Answers 3

10

Sorry to say this, but the answers you have received are bad habits that you should stay away from. A better programming practice, and perhaps the proper programming practice, would be to pseudo-namespace your global variables so to not clutter the Global namespace/scope. The reasoning behind this is to make your code more manageable, and more importantly, make life easier for you if/when your application becomes large. A simple mechanism to define a namespace is to use the module-pattern made famous by Douglas Crockford.

Here's a simple example:

var myNamespace = function(){
  var o = {};
  var globals = {};

  var setGlobVar = function(name, value) {
    globals[name] = value;
  };

  var getGlobVar = function(name) {
    if (globals.hasOwnProperty(name)) {
      return globals[name];
    } else {
      // return null by default if the property does not exist 
      return null;
    }
  };

  o.setGlobVar = setGlobVar;
  o.getGlobVar = getGlobVar;
  return o;
}();

To use this, you simply call it like methods of an object.

myNamespace.setGlobVar("secret_msg", "Dumbledore dies, so does Hedwig");
myNamespace.getGlobVar("secret_msg");

You could also expose the globals variable instead of using the setGlobVar and getGlobVar methods to use it, if you wanted to simplify how you access the variable.


The point is to stay away from defining variables in the global namespace (i.e., the window object) as much as possible, by creating a namespace of your own. This reduces the chance of name collisions, accidentally rewrites or overrides, and again, global namespace clutter.

An even simpler approach to doing this is to simply define an object and augment its properties.

var globals = {};
globals.SECRET_MSG = "Snape is not a traitor"

Though I would extend this approach by wrapping globals into a namespace that is specific to my application.

var myNamespace = {};
myNamespace.globals = {};
myNamespace.globals.SECRET_MSG = "Snape is not a traitor"

NOTE: This is actually the same as original module-pattern approach I suggested, just without the get and set accessor methods and coded differently.

Sign up to request clarification or add additional context in comments.

4 Comments

Hmm this looks interesting too, but I don't really understand the whole thing :), How should I use this? :\ But as I understood the variables what I wanted to add to window to create a global variable you say that I should add it to another variable? so for example, globalVars.variable?
That way would work as well. The point is to stay away from defining variables in the Global namespace (i.e., the window object) by creating your own namespace. The method I proposed above may be overkill for what you need, but it is worth learning if you plan on doing any Javascript development.
Added more detail to my answer at the bottom.
Very nice answer, but one thing: please, please remove the Harry Potter references! XD Think about the children! Won't somebody please think about the children! ;) cheers!
1

Call the function as globVar('myVar','myVarValue')

function globVar(variable,value){
   window[variable] = value;
}

Here is a jsfiddle: http://jsfiddle.net/emQQm/

9 Comments

hmm looks interesting let me try it ;)
Of course, the question is: why does this matter? Why not just write window[variable] = value and be done with it?
Ok this works! Thanks, but please could you tell me how should I call the global variable with a variable? so you wrote alert(myVar); which is good if I know the name of the variable what was created, and another problem is that I don't know how to call it because If I want to call it with a variable (for example alert(variable)) what calls the global variables value because variable is reserved inside the function.. oh this is a bit complicated :))
So you are trying to access a variable you don't know the name of? More examples would be helpful.
yes I don't know them because It will be created by the user. @Lime
|
0

window.variable = variable;

Don't understand what is an "automatic mode", so this might not what you wanted.

9 Comments

I show you a function, but I don't think that will work :), but I would like to have that way, for example I could create a global variable just like this: globVar('myVariable'); then myVariable is added to the global variables.
There is no need to "add" it to the global variables - when you do window.variable = 123;, you assign a value that you are going to use from now on.
If you just want to get data set by users, you can use something like: window.variablesFromUsers = {};. Then your users can do something like: window.variablesFromUsers['abc'] = 123; and you will be able to get it in the same way: window.variablesFromUsers['abc'] will give you 123. If you want to get all the variables set by users, you can do: for v in window.variablesFromUsers and in the loop get all the names ('abc' in the previous example), then do window.variablesFromUsers[o] to get the contents (123 in the example). Hope this helps.
Sorry, but I have to say that it is not a good programming practice to define global variables in this manner.
@Johh Can you clarify what you meant - it's not a good practice to define global variables (agree with that, but that's what OP asked - it might be required given the context, e.g. interfacing legacy libraries) or in this manner? If latter, can you let me know why do you think that?
|

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.