Possible Duplicate:
How to declare a global variable in a .js file
I need to set a variable in a script I'm developing as global. How do I do that? Thanks in advance!
Possible Duplicate:
How to declare a global variable in a .js file
I need to set a variable in a script I'm developing as global. How do I do that? Thanks in advance!
Declare it in the global execution context (not in the scope of a function):
var x = "hello";
Declare it as an implicit property of the global object (be careful, people may think you've made a mistake and missed the var
, and this will throw a reference error in strict mode, so don't use it):
x = "hello";
Declare it as an explicit property of the global object:
window.x = "hello";
Keep in mind that window
is specific to the browser environment. If you are working with node a global object that is available in all contexts is global
:
global.x = "hello";
Just define a variable outside any function:
var myGlobalVariable = 42;
Just don't go overboard on global variables as it will make your code harder to read and debug.
Like this
<script>
var myGlobal = 2;
function xyz()
{
//can access myGlobal here
}
</script>
There's a good article on Javascript scope here - basically anything defined outside is accessible inside, but not vice versa.