Javascript教程:delete删除对象(3)
属性特性
现在变量会怎样已经很清楚(它们成为属性),剩下唯一的需要理解的概念是属性特性。每个属性都有来自下列一组属性中的零个或多个特性--ReadOnly, DontEnum, DontDelete 和Internal,你可以认为它们是一个标记,一个属性可有可无的特性。为了今天讨论的目的,我们只关心DontDelete 特性。
当声明的变量和函数成为一个可变对象的属性时--要么是激活对象(Function code),要么是全局对象(Global code),这些创建的属性带有DontDelete 特性。但是,任何明确的(或隐含的)创建的属性不具有DontDelete 特性。这就是我们为什么一些属性能删除,一些不能。
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"
内置对象和DontDelete
这就是全部:属性中一个独特的特性控制着这个属性是否能被删除。注意,内置对象的一些属性也有特定的DontDelete 特性,因此,它不能被删除。特定的Arguments 变量(或者,正如我们现在了解的,激活对象的属性),任何函数实例的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" })();
与函数参数相对应的创建的属性也有DontDelete 特性,因此也不能被删除。
(function(foo, bar){ delete foo; // false foo; // 1 delete bar; // false bar; // 'blah' })(1, 'blah');
未声明的赋值
您可能还记得,未声明的赋值在一个全局对象上创建一个属性。除非它在全局对象之前的作用域中的某个地方可见。现在我们知道属性分配与变量声明之间的差异,后者设置了DontDelete 特性,而前者没有--应该很清楚未声明的赋值创建了一个可删除的属性。
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"
请注意,该特性是在属性创建的过程中确定的(例如:none)。后来的赋值不会修改现有属性已经存在的特性,理解这一点很重要。
/* `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"