What's the difference between window.x and x?

前端 未结 2 1962
死守一世寂寞
死守一世寂寞 2021-01-20 16:29

Let\'s say, \"x\" is a variable that never defined, so it should be undefined. In the following scenario:
1)

if(x){//do something}
//ReferenceError: x is         


        
2条回答
  •  鱼传尺愫
    2021-01-20 16:55

    x will only be the same as window.x if it was declared (in the global scope, naturally). That can be done with an explicit var statement in the global scope, or a simple assignment without var in any scope (which is considered an implicit global declaration):

    var a; // declares global a
    function foo() {
        b = 10; // declares (implict) global b
    }
    

    Both a and b will also be available as window.a and window.b in web browsers.

    This also creates a global variable on browsers:

    window.c = 20; // can be accessed as just c
    

    Now, trying to access a non-existing variable throws a ReferenceError, while trying to access a non-existing object property just returns undefined.

    Interesting fact: globals created with var can't be removed with the delete operator, while implicit globals and those created as properties of the global object can.

提交回复
热议问题