Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

What is the purpose of the delete operator in Javascript?

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.

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...