Why does the following work
var NameSpace = NameSpace || {};
NameSpace.Foo = 2;
But this does not?
var NameSpace = NameSpace || {};
var NameSpace.Foo = 2;
Any insight into the inner workings of the variable deceleration in regards to namespaces would be appreciated.
JavaScript does not have namespaces. Your first line of code is declaring a variable whose name is Namespace
, and whose value is an object:
var NameSpace = NameSpace || {};
Then you create a property Foo
on the object, and assign a value to it:
NameSpace.Foo = 2;
Bottom line: variables and object properties are different things (among other differences, variables have scope, while properties don't). The var
statement is only for declaring variables.