سؤال

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.

نصائح أخرى

var foo = foo;

works because ECMAscript will decouple this line in away like

var foo;
foo = foo;

under the hood. This concept is commonly called hoisting.

Your second snippet can't work, since we are assigning an object property. The var keyword always implies, that we want to create a variable, a symbol so to speak, within the current Execution Context.

What you could do of course, is

var Foo = NameSpace.Foo = 2;

This would

  • create the variable Foo in the current context
  • assign the object property Foo on the NameSpace object
  • assign both the value of 2

var is reserved for declaring new variables, not modifying existing ones.

Additionally . is an invalid character for a variable name.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top