Reputation: 6879
Say I'm trying to create a global variable x if it doesn't already exist:
x = x || {}; //This fails. x is not defined
this.x = this.x || {}; //But this works
I'm running this in Firebug and was surprised that the 1st line failed. I expected x to be attached to the global window object, but it didn't work unless I specified the this
.
I'm hoping to improve my understanding of the language. Can someone explain to me why this is?
Thanks for any help.
Upvotes: 2
Views: 47
Reputation: 75327
If you try and use an undeclared variable a part of an expression, you'll get a ReferenceError
thrown.
If you try and assign an undeclared variable, the variable will be declared as an implicit global. Implicit globals are bad.
x = x || {};
^ its this x that breaks it.
To correctly check whether a variable is declared, you should use the typeof variable === "undefined"
check.
Undefined attributes however (in your second example, x
is an attribute on this
), hold the value undefined
by default.
Upvotes: 2