PDA

View Full Version : Making a Global Variable from Inside a Function?



???
06-17-2007, 04:29 PM
I was just wondering if it was possible to make a global variable from inside a function. Like:

function blah () {
var lol = "bye";
}

But make it so then you could use it in some other function. Like maybe:

function alerter () {
alert(lol);
}

I'm still developing my style of coding and this would be useful to know how to do (if possible).

mwinter
06-17-2007, 05:01 PM
I was just wondering if it was possible to make a global variable from inside a function.

A variable, in a literal sense (see your deletion thread), can only be defined using a var declaration, therefore the statement must occur outside any function. However, a property can be created at any time, provided you have a reference to the object.



var global = this; // You can use window, but I prefer not to.

function foo() {
global.property = 'value';
}

If the variable is predictable, I would suggest that you just declare it and reserve the above for cases where run-time creation really are necessary - for example, when the property name is chosen dynamically. Using a declaration makes it clear what variables exist, rather than forcing one to look through every line of code for an assignment.

Twey
06-17-2007, 08:29 PM
It's also usually a sign of bad code that it uses global variables. If you really must have global variables, you should create a single namespacing object and keep all the variables within that. If you find yourself using global variables a lot, then chances are there's a better way to accomplish whatever you're doing.

mwinter
06-17-2007, 08:36 PM
If you really must have global variables, you should create a single namespacing object and keep all the variables within that.

I don't really like "namespaces" in scripts. It's cumbersome and adds a performance penalty. Using a function expression called immediately avoids creating global variables, with only a one-off penalty rather than a cumulative one:



(function () {
var sortOfGlobal;

/* ... */
})();

Twey
06-17-2007, 08:40 PM
I don't really like "namespaces" in scripts. It's cumbersome and adds a performance penalty.A matter of taste, I think. Personally, I'd take the small performance penalty in exchange for increasing the modularity of my script, especially if it were a large one.

The function expression does help avoid conflicts, but there are other benefits to namespacing.