How can I make a local variable inside a function into a global in JavaScript?
P.S: Just pure JavaScript, no jQuery.
P.P.S.: Nothing toooo complicated, thanks. :)
How can I make a local variable inside a function into a global in JavaScript?
P.S: Just pure JavaScript, no jQuery.
P.P.S.: Nothing toooo complicated, thanks. :)
You can do the following to access a global inside of a function.
Any variable created outside the scope of a function can be referenced inside of a function.
Var myGlobalVar;
Function myFunction(){
if(....) {
myGlobalVar = 1;
}
}
You don't.
You can copy a local variable to the global scope by doing window.myVar = myVar
(replacing window
by whatever is your global object), but if you reassign the local one, the global copy won't follow.
You can assign a key to the window
object. It'll be a global variable.
function foo(){
var bar1; // Local variable
bar1 = 11;
window.bar2 = bar1; // bar2 will be global with same value.
}
Or
In pure JavaScript, if you will declare a variable without var
anywhere, it will be in the global scope.
function foo(){
var bar1; // Local variable
bar1 = 11;
bar2 = bar1; // bar2 will be global with same value.
}
Note: In the above text, if bar2
won't be declared yet, it will go to the window
scope, otherwise it will just update bar2
. If you want to make sure about using the global one, use like window.bar2 = bar1
.