Does delete have any purpose that cannot be acheived by reassignment to undefined?
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.
let 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
EDIT: As T.J. Crowder explains:
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
.
This matters in its own right, but it also matters when you're using inheritance, because if O derives from P
let P = { prop: 42 };
let O = Object.create(P); // P is O's prototype.
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.
console.log(O.prop); // "42" since O doesn't have its own prop, but P does.
O.prop = undefined;
console.log(O.prop); // "undefined" since O has its own prop.
delete O.prop;
console.log(O.prop); // "42" since the delete "unmasked" P.prop.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…