It turns out that there is a similar question, What does “options = options || {}” mean in Javascript?, but that question is general - I am specifically asking about the occurrence of such a statement at the top of a Javascript file. I already understand that if foo
is not already defined then it will be initialized with an empty object. Again, my question specifically asks about this usage as the first statement at the top of a Javascript file. Why would one do that? To prevent the object being overwritten by an assignment from a file loaded earlier? In the case I found, there are no files loaded earlier - hence my question:
Question: What is the point of window.foo
in the following statement, which is the first statement at the top of a Javascript file (i.e. as opposed to just saying foo = {};
)?
foo = window.foo || {};
Note that subsequent lines in the file define properties and methods:
foo.one = 'one';
foo.two = function() {
return 1+1;
}
They are used as foo.one;
and foo.two();
(Follow-up) Question 2: What is the advantage (and the difference in terminology) of the above approach compared to defining those very same things as follows:
var one = 'one';
function two() {
return 1+1;
}
They are used as one;
and two();
Additionally, all of the above are also accessible via window
: window.foo.one;
and window.one;
and window.foo.two();
and window.two();
.
(Follow-up) Question 3: Is everything I define at the outermost scope bound to window
? And what's the point of that? (i.e. What if it wasn't?)