Pergunta

I got this question in an interview and I am curious as to why the two output different things:

(function() {
    console.log(bar);
    console.log(baz);
    foo();

    function foo() {
        console.log('aloha');
    }

    var bar = 2;
    baz = 3;
})();

ouputs:

undefined
Uncaught ReferenceError: baz is not defined 

whereas:

(function() {
    console.log(bar);
    console.log(window.baz);
    foo();

    function foo() {
        console.log('aloha');
    }

    var bar = 2;
    baz = 3;
})();

outputs:

undefined
undefined
'aloha'

what is the difference in the way that baz and window.baz are referenced? I though globals were automatically attached to window?

Foi útil?

Solução

A ReferenceError indicates that an invalid reference value has been detected (ECMA 5 15.11.6.3)

In practical terms, this means a ReferenceError will be thrown when JavaScript attempts to get the value of an unresolvable reference. (There are other cases where a ReferenceError will be thrown, most notably when running in ECMA 5 Strict mode. If you’re interested check the reading list at the end of this article)

For further reading take a look here.

Outras dicas

This is because console.log(window.baz); is trying to find the variable inside window object where as console.log(baz) is trying to get a standalone variable, which is not defined yet.

Because function definitions are evaluated before execution, variable assignment expressions are not.

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