简体   繁体   English

简单对象的Javascript内存泄漏

[英]Javascript Memory leak for simple object

I am looking for some very basic examples of memory leaks in JavaScript and how to fix them. 我正在寻找一些非常基本的JavaScript内存泄漏示例,以及如何修复它们。 Specifically, if I do something like this in my code; 具体来说,如果我在代码中执行类似的操作;

var obj = new MyObj();

Do I have to take care of something or do some steps explicitly so that obj does not leak? 我是否需要照顾某些事情或明确地执行一些步骤,以免obj泄漏? Or do I not have to worry about anything? 还是我不必担心任何事情? Will it get garbage collected automatically by the browser ? 浏览器会自动收集垃圾吗?

Are there any cross-browser differences in how memory handling is done (wrt DOM or any other objects) ? 浏览器在完成内存处理(wrt DOM或任何其他对象)的方式方面是否存在跨浏览器差异?

我想您可以在此页面找到答案Javascript内存管理

A short summary: Objects will be garbage collected by the browser automatically when the object has no more references to it. 简短摘要:当对象没有更多引用时,浏览器会自动将其垃圾回收。

So doing 这样做

var obj = {}; obj = null;

will cause obj to be garbage collected at same random point in the future, you can not explicitly tell the browser to garbage collect this object. 将来会导致在同一随机点对obj进行垃圾回收,因此您无法明确告知浏览器对该对象进行垃圾回收。 Off course this is something you will usually not be doing, since object references usually go out of scope. 当然,您通常不会这样做,因为对象引用通常超出范围。

Example: 例:

function foo() {
 var obj = {};
}
foo();

After this function call, the obj variable doesn't exist anymore and goes out of scope, the object that was being referenced by obj is now a candidate to be garbage collected. 在此函数调用之后, obj变量不再存在并且超出范围,由obj引用的obj现在是要进行垃圾收集的候选obj

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM