Javascript delete 引用类型对象

it2022-05-09  27

       很少使用javascript的delete,最近因为一个小bug发现删除引用类型对象的时候有一点不同。如下面例子:

 

var testVar = { a : { test : 1 } }, test1 = {}, test2 = {}; test1.a = testVar.a; test2.a = testVar.a; /* delete test1.a; console.log(test1.a); // undefined console.log(test2.a); // Object {test: 1} console.log(testVar.a); // Object {test: 1} */ delete testVar.a; console.log(test1.a); // Object {test: 1} console.log(test2.a); // Object {test: 1} console.log(testVar.a); // undefined

 

通过测试可以看出,javascript的delete删除的对象如果是一个引用类型,那它删除的不是引用的对象,而是指向该引用对象的指针。因此,即使 delete testVar.a ,test1.a指向的对象仍然没有删除。

 

       更多关于javascript delete关键字的原理,推荐:

       http://perfectionkills.com/understanding-delete/

       翻译版本:

       http://www.ituring.com.cn/article/7620

 

 

转载于:https://www.cnblogs.com/Kingle/p/3344648.html


最新回复(0)