Pergunta

I came across this pattern for JavaScript initialization:

foo = foo || {};
alert('no errors!');

But it seems that it does not work unless foo was defined before.

There are two variations of the same pattern that seem to work correctly:

var foo = foo || {};
alert('no errors!');

and

foo = window.foo || {};
alert('no errors!');

From my point of view, I don't understand why the first one does not work, but the two other do.

Why is that? Could you please explain in detail?

Foi útil?

Solução

Javascript has a global object. In the browser, this is referenced by the name window.

window.foo create a property in the global object.

var foo create a global variable. This is very similar to a property of the global object, but you can't use delete on it.

Simply declaring foo without the var keyword also create a property on the global object. It is a language design choice -- a lousy one -- but a design choice none-the-less.

var foo and window.foo both work equally well when you are at the global level. If you are inside of a function -- perhaps a module -- you must use window.foo to make sure you reach the global object.

Outras dicas

You can't read a variable which isn't defined (that's a reference error). That's why

something = foo;

will lead to an error if the foo variable isn't declared. window is declared of course and there's no problem querying its property foo.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top