Can't understand the behavior of deleting vars in JavaScript

后端 未结 3 1523
后悔当初
后悔当初 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:24

    You can use delete only for deleting objects, object properties or array element.

    delete expression

    delete will be not working if expression can't be represented as property. So delete can remove global variable, but not variables inited by var.

    So, let me explain:

    var x = 5;
    

    You create variable in global scope by var, not property of window object. This var is just linked to window.x. And then you compare window.x === x it will return true. But:

    delete x; // deleting variable, not property, return false
    delete window.x; // resolve link to x and also deleting variable, not property, return false
    

    BUT

    window.x = 5;//add property
    delete window.x; // can delete property, return true
    

    AND

    window.x = 5;//add property
    delete x; //resolve x. it's a propery of window, return true
    

    and older

    In ECMAScript 262/3 as @Peter explain is available DontDelete flag. But in ECMAScript 262/5.1 in strict mode deleting is regulated by Configurable flag:

    When a delete operator occurs within strict mode code, a SyntaxError exception is thrown if its UnaryExpression is a direct reference to a variable, function argument, or function name. In addition, if a delete operator occurs within strict mode code and the property to be deleted has the attribute { [[Configurable]]: false }, a TypeError exception is thrown.

提交回复
热议问题