javascript var 声明:用var 声明的变量是不能被删除的。

Posted by bower on October 05, 2011
javascript

分享给你的朋友->bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark

We see that at this phase there is no any “b” since it is not a variable, “b” will appear only at code execution phase (but in our case won’t since there is an error).

Let’s change the code:

alert(a); // undefined, we know why
b = 10;
alert(b); // 10, created at code execution
var a = 20;
alert(a); // 20, modified at code execution

There is one more important point concerning variables. Variables, in contrast with simple properties, have attribute {DontDelete}, meaning impossibility to remove a variable via the delete operator:

// 用var 声明的变量是不能被删除的。

a = 10;
alert(window.a); // 10
alert(delete a); // true
alert(window.a); // undefined
var b = 20;
alert(window.b); // 20
alert(delete b); // false
alert(window.b); // still 20

But there is one execution context on which this rule does not affect; it is the eval context: there{DontDelete} attribute is not set for variables:

eval('var a = 10;');
alert(window.a); // 10
alert(delete a); // true
alert(window.a); // undefined

For those who test these examples in console of some debug tool, e.g. Firebug: notice, that Firebug alsouses eval to execute your code from the console. So there vars also do not have {DontDelete} and can be deleted.

 

 

 

 

分享到:人人网开心网腾讯微博新浪微博豆瓣分享腾讯空间百度搜藏腾讯书签

分享给你的朋友->bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word