Javascript has function scope. This means that every variable declared within a function, will only be accessible from within that function.
If you’d properly declared the objectX variable with var
, as follows:
function X() {
...
var objectX = {};
...
return objectX;
}
then objectX
would only be known as objectX
inside the X
function. Elsewhere, it would be known as whatever variable you’d assigned it to. Since in your code, you don’t assign the result of X()
to anything, objectX
would not be accessible from anywhere.
However, here’s one of Javascript’s more serious design flaws: if you don’t explicitly declare a variable (using the var
statement, or as a function parameter), that variable will automatically become a global variable. That means that it will be accessible anywhere.
Because of this, in your code above, you can access objectX
everywhere by that name.
anObject
, on the other hand, is properly declared (as a parameter), and that means its scope will be limited to the Z
function.
In short, the way your code is written, objectX
is accessible everywhere by way of the objectX
variable, and inside the function Z
, you can reference it both as objectX
and as anObject
.
Do note, however, that global variables are a Bad Thing™, since they can make it quite hard to figure out what variable gets assigned by who, when, and why — as you’ve noticed.
While Javascript makes it impossible to completely avoid them, as a rule you should try to keep the scope of your variables as small as possible (scope = where in your program that variable can be accessed).
To that end, I would recommend refactoring your code like igorw has.
X
function is never called: Javascript is case-sensitive, sox()' is something different than
X()`... – Martijn Feb 8 '11 at 16:01