您的位置:首页 > Web前端 > JavaScript

JavaScript中对象property的删除方法介绍

2014-12-30 00:00 543 查看
JavaScript中,可以使用delete操作符来删除对象中的property:
var t = {a:42, b:26};

console.log(t);//Object {a=42, b=26}

delete t.a;

console.log(t);//Object {b=26}

这种property删除操作的局限性在于:delete操作符只能删除对象自身所有的property,无法删除其从prototype对象处继承而来的property。如果想删除prototype对象中的property,必须显式获取prototype对象后,在prototype对象中进行操作:
var o = {x:1, y:2};

var a = Object.create(o);

a.z = 3;

console.log(a);//Object {z=3, x=1, y=2}

delete a.x;//Can NOT delete inherited property

console.log(a);//Object {z=3, x=1, y=2}

delete a.z;//Can delete own property

console.log(a);//Object {x=1, y=2}

delete a.__proto__.x;

console.log(a);//Object {y=2}

如果删除了prototype对象中的property,那么所有从该prototype对象中继承的对象都会收到影响。


对于delete操作的返回值,JavaScript中遵循以下规则:



1.如果delete操作成功,返回true。

2.如果delete操作无任何效果(比如要删除的property并不存在),也返回true。

3.如果要delete的property,其configurable属性为false,那么在严格模式下会报TypeError错误,而在非严格模式下则返回false。

如果delete操作符所作用的是全局对象的property,那么在非严格模式下,代码中的全局对象可以省略:
this.c = 42;

delete c;//equal to delete this.c;

需要注意的是,在严格模式下,上述写法会抛SyntaxError错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: