delete operator with var and non var variables

后端 未结 4 1510
感情败类
感情败类 2020-12-03 19:42

I tried delete a variable in javascript using delete operator, but found some issue. Can you guys please explain the below code, and why it is happening

>         


        
4条回答
  •  没有蜡笔的小新
    2020-12-03 20:28

    When a variable is created using a variable declaration (i.e. using var) then it is created with its deleteable flag set to false.

    When a variable is created implicitly by assignment without being declared, its deleteable flag is set to true.

    It is a peculiarity of the global execution context that variables are also made properties of the global object (this doesn't happen in function or eval code). So when you do:

    var a;
    

    Then a is a variable and also a property of the global (window in a browser) object and has its deleteable flag set to false. But:

    a = 'foo';
    

    creates a as a global variable without a declaration, so its deleteable flag is set to true.

    The result is that you can delete global variables created implicitly, but not those created by declarations (including function declarations).

提交回复
热议问题