开发者

what exactly is the difference between doing abc.p = undefined and delete abc.p

I have an object referred to by the variable a开发者_如何学运维bc

Besides the return value of the expressions, what exactly is the difference between doing abc.p = undefined and delete abc.p


> abc.p = undefined
undefined

> 'p' in abc
true

> delete abc.p
true

> 'p' in abc
false

Assigning a member to undefined doesn't make the member go away. It still occupies a place in the object (but its value is undefined). delete-ing it will actually remove the member.


In this context, they serve the same purpose.

var abc = {};

abc.p = "hello";
alert(typeof abc.p);//string
delete abc.p;
alert(typeof abc.p);//undefined

abc.p = "hello world";
alert(typeof abc.p);//string
abc.p = undefined;
alert(typeof abc.p);//undefined

Here is a detailed explanation on delete: Understanding Delete by Kangax


abc.p = undefined will not remove the property, i.e. it's still listed when iterating over the object. delete abc.p will remove it.


abc.p = undefined will keep the property to the object but its value will be undefined.

The delete abc.p will remove the property completely from the object.


One exception is when using "with" statement:

abc.p = undefined;
with(abc) {alert(p);} // shows: "undefined"

delete abc.p;
with(abc) {alert(p);} // an error occurs: "ReferenceError: p is not defined"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜