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

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

    They're available only in the function they're declared in.

    Function scope is the only other scope in JavaScript, btw, unlike block-scoping in other {} languages.)

    Re: your edit Don't be fooled--JS's this semantics are a bit irksome IMO--this may not be what you expect under a variety of circumstances.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题