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

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

    To cite http://perfectionkills.com/understanding-delete/#execution_context:

    Every execution context has a so-called Variable Object associated with it. Similarly to execution context, Variable object is an abstract entity, a mechanism to describe variable instantiation. Now, the interesing part is that variables and functions declared in a source text are actually added as properties of this Variable object.

    When control enters execution context for Global code, a Global object is used as a Variable object. This is precisely why variables or functions declared globally become properties of a Global object

    Yet, these Variable Objects are not accessible. The only non-internal one is the global object, window or this (in global context).

    The relevant section in the specification is #10: Executable Code and Execution Contexts.

提交回复
热议问题