Javascript中删除运算符的用途是什么? [英] What is the purpose of the delete operator in Javascript?

查看:117
本文介绍了Javascript中删除运算符的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

删除操作符的行为似乎是非常复杂,并且对实际操作有很多误解。对我而言,似乎将某些内容重新分配给 undefined 将更可靠地完成您所期望的。

The behaviour of the delete operator seems very complicated and there are many misunderstandings about what it actually does. To me, it seems that reassigning something to undefined will more reliably do what you would expect.

我已经从未见过在非示例代码中实际使用的Javascript中的 delete 关键字,我想知道它是否对任何事情特别有用。 删除是否有通过重新分配到 undefined 无法实现的目的?是否使用了在所有着名的库中(例如jQuery,dojo,backbone等)?

I've never seen the delete keyword in Javascript actually used in non-example code and I am wondering if it is particularly useful for anything. Does delete have any purpose that cannot be acheived by reassignment to undefined? Is it used at all in any of the famous libraries (e.g. jQuery, dojo, backbone, etc)?

推荐答案


删除是否有任何无法通过重新分配到未定义的目的?

Does delete have any purpose that cannot be acheived by reassignment to undefined?

是。如果要从原型中取消屏蔽属性或在中导致 hasOwnProperty , (... in ...)不将该属性记录为现有属性,然后 delete 是合适的。

Yes. If you want to unmask a property from a prototype or cause in, hasOwnProperty, and for (...in...) to not record the property as existing then delete is appropriate.

var set = {};

set._x = true;

alert('_x' in set);  // true

set._x = undefined;

alert('_x' in set);  // true

delete set._x;

alert('_x' in set);  // false

编辑:作为T.J. Crowder解释说:

As T.J. Crowder explains:


delete 运算符的目的是完全删除属性从一个对象,而将属性设置为 undefined 只是将属性设置为 undefined

The purpose of the delete operator is to completely remove a property from an object, whereas setting a property to undefined just sets the property to undefined.

这本身就很重要,但是当你使用继承时它也很重要,因为如果O派生自P

This matters in its own right, but it also matters when you're using inheritance, because if O derives from P



var P = { prop: 42 };
var O = Object.create(P);  // P is O's prototype.




当您检索 O.prop ,如果O具有该名称的属性(即使其值未定义),则从O获取prop的值,但如果O根本没有该属性,则将从 P.prop 代替。

when you retrieve O.prop, you get the value of prop from O if O has a property with that name (even if its value is undefined), but if O doesn't have the property at all, then the value will be retrieved from P.prop instead.



alert(O.prop);  // "42" since O doesn't have its own prop, but P does.
O.prop = undefined;
alert(O.prop);  // "undefined" since O has its own prop.
delete O.prop;
alert(O.prop);  // "42" since the delete "unmasked" P.prop.

这篇关于Javascript中删除运算符的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆