熟悉c++的都知道,new用来获取资源,delete用来释放资源。但是在javascript中则不是这样。下面是stackoverflow上的高赞回答:
https://stackoverflow.com/questions/4869712/new-without-delete-on-same-variable-in-javascript#:~:text=new%20is%20for%20creating%20objects,the%20property%20that%20you%20removed).
new
and delete
have nothing whatsoever to do with each other in JavaScript (despite their confusing similarity to completely different constructs in other languages). Don't worry about creating objects (new
) without explicitly cleaning them up, that's the garbage collector's job.
new
is for creating objects via constructor functions. delete
, on the other hand, is for removing properties from objects. It has nothing to do with removing an object from memory, other than as a side effect (e.g., if the only outstanding reference to that object was from the property that you removed).
Example of correct use of delete
:
var obj = {};
obj.foo = "bar"; // Now `obj` has a property called `foo`
delete obj.foo; // Now it doesn't
javascript中的new 和delete相互没有关系。假如你new了一个对象,但是又没有释放,也不要担心。js的垃圾回收机制会处理的。
new通过构造函数来创建对象。而delete,是删除对象的一个属性的。除非属性被删除后,该属性指向的对象再也没有被其他的变量索引到,此时才会引起内存中的对象被释放。