屬性特性
現(xiàn)在變量會怎樣已經(jīng)很清楚(它們成為屬性),剩下唯一的需要理解的概念是屬性特性。每個屬性都有來自下列一組屬性中的零個或多個特性--ReadOnly, DontEnum, DontDelete 和Internal,你可以認(rèn)為它們是一個標(biāo)記,一個屬性可有可無的特性。為了今天討論的目的,我們只關(guān)心DontDelete 特性。
當(dāng)聲明的變量和函數(shù)成為一個可變對象的屬性時--要么是激活對象(Function code),要么是全局對象(Global code),這些創(chuàng)建的屬性帶有DontDelete 特性。但是,任何明確的(或隱含的)創(chuàng)建的屬性不具有DontDelete 特性。這就是我們?yōu)槭裁匆恍⿲傩阅軇h除,一些不能。
var GLOBAL_OBJECT = this ;
/* `foo` is a property of a Global object.
It is created via variable declaration and so has DontDelete attribute.
This is why it can not be deleted. */
var foo = 1;
delete foo; // false
typeof foo; // "number"
/* `bar` is a property of a Global object.
It is created via function declaration and so has DontDelete attribute.
This is why it can not be deleted either. */
function bar(){}
delete bar; // false
typeof bar; // "function"
/* `baz` is also a property of a Global object.
However, it is created via property assignment and so has no DontDelete attribute.
This is why it can be deleted. */
GLOBAL_OBJECT.baz = 'blah' ;
delete GLOBAL_OBJECT.baz; // true
typeof GLOBAL_OBJECT.baz; // "undefined"
內(nèi)置對象和DontDelete
這就是全部:屬性中一個獨(dú)特的特性控制著這個屬性是否能被刪除。注意,內(nèi)置對象的一些屬性也有特定的DontDelete 特性,因此,它不能被刪除。特定的Arguments 變量(或者,正如我們現(xiàn)在了解的,激活對象的屬性),任何函數(shù)實(shí)例的length 屬性也擁有DontDelete 特性。
function (){
/* can't delete `arguments`, since it has DontDelete */
delete arguments; // false
typeof arguments; // "object"
/* can't delete function's `length`; it also has DontDelete */
function f(){}
delete f.length; // false
typeof f.length; // "number"
})();
與函數(shù)參數(shù)相對應(yīng)的創(chuàng)建的屬性也有DontDelete 特性,因此也不能被刪除。
( function (foo, bar){
delete foo; // false
foo; // 1
delete bar; // false
bar; // 'blah'
})(1, 'blah' );
未聲明的賦值
您可能還記得,未聲明的賦值在一個全局對象上創(chuàng)建一個屬性。除非它在全局對象之前的作用域中的某個地方可見。現(xiàn)在我們知道屬性分配與變量聲明之間的差異,后者設(shè)置了DontDelete 特性,而前者沒有--應(yīng)該很清楚未聲明的賦值創(chuàng)建了一個可刪除的屬性。
var GLOBAL_OBJECT = this ;
/* create global property via variable declaration; property has <STRONG>DontDelete</STRONG> */
var foo = 1;
/* create global property via undeclared assignment; property has no <STRONG>DontDelete</STRONG> */
bar = 2;
delete foo; // false
typeof foo; // "number"
delete bar; // true
typeof bar; // "undefined"
請注意,該特性是在屬性創(chuàng)建的過程中確定的(例如:none)。后來的賦值不會修改現(xiàn)有屬性已經(jīng)存在的特性,理解這一點(diǎn)很重要。
/* `foo` is created as a property with DontDelete */
function foo(){}
/* Later assignments do not modify attributes. DontDelete is still there! */
foo = 1;
delete foo; // false
typeof foo; // "number"
/* But assigning to a property that doesn't exist,
creates that property with empty attributes (and so without DontDelete) */
this .bar = 1;
delete bar; // true
typeof bar; // "undefined"
出處:
責(zé)任編輯:bluehearts
上一頁 理解delete [2] 下一頁 理解delete [4]
◎進(jìn)入論壇網(wǎng)頁制作、WEB標(biāo)準(zhǔn)化版塊參加討論,我還想發(fā)表評論。
|