使用var和非var变量删除运算符 [英] delete operator with var and non var variables
问题描述
我尝试使用delete运算符在javascript中删除变量,但发现了一些问题。
你们可以解释下面的代码,以及它为什么会发生
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
>> var a = 5;
>> delete a
false
>>a
5
>> b=5;
>>delete b
true
>>b
ReferenceError b is not defined
为什么var a = 5和b = 5不同?
why var a = 5 and b = 5 are different?
推荐答案
当使用变量声明(即使用 var )创建变量时,会创建变量并将其deleteable标志设置为 false 。
When a variable is created using a variable declaration (i.e. using var) then it is created with its deleteable flag set to false.
当变量由赋值隐式创建而未声明时,其可删除标志设置为 true 。
When a variable is created implicitly by assignment without being declared, its deleteable flag is set to true.
全局执行上下文的一个特点是变量也是全局对象的属性(这不会发生在函数或eval代码中)。所以当你这样做时:
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;
然后 a 是变量,也是全局的属性(窗口)在浏览器中)对象并将其可删除标志设置为 false 。但是:
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';
将 a 创建为没有声明的全局变量,因此其可删除标志设置为 true 。
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).
这篇关于使用var和非var变量删除运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!