How do JavaScript variables work?

后端 未结 5 2118
星月不相逢
星月不相逢 2020-12-03 11:40

I know that JavaScript vars point to a value:

var foo = true;
//... later 
foo = false;

So in that example I\'ve changed foo p

5条回答
  •  星月不相逢
    2020-12-03 12:10

    Tools like JSLint recommend that you put all your var statements at the top of functions. It's because JavaScript essentially does it for you if you don't, so it's less confusing if you do. In your example, it doesn't matter where you put var as long as it occurs before one definition of myvar. Likewise, you may as well declare i at the top of the function as well.

    What's more interesting is the hierarchical scope chain in which JavaScript searches for names when it wants to look one up. It searches up the scope chain from local to global until it finds the first instance of said name.

    Which is why you can play games like this to annoy your friends:

    function foofinder() {
        var bar = function () { return foo; },
            foo="beers";
        return bar();
    }
    
    foofinder();
    >>> "beers"
    

提交回复
热议问题