I have a questions regarding variable scope in Javascript. I have a series of scripts on a webpages loading at different times. I need a global object called MyVar for example to be accessible to them all. I want to avoid redefining it but I guess it has to be defined at some point by the first script. My question is is using var MyVar = MyVar || {}
a solution?
Thanks
/**
* Script 1
*/
var MyVar = MyVar || {};
MyVar.config = {
x : 2,
y : 3
};
/**
* Script 2
*/
//is this correct?
var MyVar = MyVar || {};
//to which MyVar am I assigning the apple property?
MyVar.apple = 'red';
UPDATE
Great answers so far guys thanks.
One last part though, what is the second var statement doing when I repeat var MyVar = MyVar || {};
for the second time? Is it creating a new var in the global scope called MyVar
that is assigned the value of the existing MyVar
?
Other posters are right to assume I have these scripts loading synchronously in <script>
tags however due to division of labour I create the scripts then don't control when and how they are loaded so need a fool-proof method to create / utilize my MyVar
object.
Thanks