Can't understand the behavior of deleting vars in JavaScript

后端 未结 3 1393
后悔当初
后悔当初 2021-01-19 22:01

Here is the issue:

var x = 5;
window.x === x // true. x, as it seems, is a property of window
delete x; // false
delete window.x; // false;

3条回答
  •  无人及你
    2021-01-19 22:18

    This is how I understand that:

    var x = 5; declared in the global scope creates the new window property x.

    window.x = 5; declared (whereever) creates the new window property x as well. That's why window.x === x gives you true.

    The difference is that javascript by default sets different descriptors for x property according to the way (one of two above) it is declared.

    var x = 5 is equal to:

    Object.defineProperty(window,'x',{
      value: 5,
      writable: true,
      enumerable: true,
      configurable: false
    });
    

    while window.x = 5 is equal to:

    Object.defineProperty(window,'x',{
      value: 5,
      writable: true,
      enumerable: true,
      configurable: true
    });
    

    The configurable descriptor, if false, forbides to delete the property. We can assume, that javascript use Object.defineProperty with different descriptor settings under the hood when we declare variables in a simple way with var keyword or without it (automatically assigned to window). You can simply check that:

    var x = 5;
    window.y = 5;
    
    console.log(Object.getOwnPropertyDescriptor(window,'x')); //configurable:false
    console.log(Object.getOwnPropertyDescriptor(window,'y')); //configurable:true
    

提交回复
热议问题