javascript中的new 和 delete

熟悉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,是删除对象的一个属性的。除非属性被删除后,该属性指向的对象再也没有被其他的变量索引到,此时才会引起内存中的对象被释放。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值