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

前端 未结 4 2057
天命终不由人
天命终不由人 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:57

    In JavaScript, all variables are assigned to some scope object. However, only the scope object of global variables is accessible in JavaScript in the browser through the window object. Variables in a function scope are assigned to some scope object used internally by the JavaScript runtime, but this cannot be accessed by the user.

    In another environment, global variables may be accessible as properties of another object (such as GLOBAL in node.js) or may be inaccessible (such as application scripts running inside the Windows Script Host).

提交回复
热议问题