Why do variables in the global scope get assigned to the window object?

前端 未结 4 2015
天命终不由人
天命终不由人 2021-01-14 14:53
var foo = \'bar\';
console.log(window.foo); // bar

Seems like variables get assigned as properties to this, but inside anonymous funct

4条回答
  •  抹茶落季
    2021-01-14 15:51

    Inside self-invoking anonymous function eg:

    function() {
        ....
    }()
    

    All variables remain inside it and do not attach themselves to global object or window. Using that technique, there are patterns created such as module/singleton pattern.

    Notice that in JS, variables have function-level scope.

提交回复
热议问题