javascript new keyword and memory leaks?

依然范特西╮ 提交于 2021-02-07 10:24:22

问题


let x = new MyClass();
...[more code]
let x = new MyClass();

Will the first instance of MyClass get garbaged collected automatically? Or do I need to explicitly x = null or something like that before the second assignment, in order to avoid a memory leak?


回答1:


JavScript's memory is managed automatically, so objects that are deemed "unreachable" are collected by the garbage collector.

In the example you provided, the object stored in x will be garbage-collected so long as it isn't reachable from other parts of your code (i.e. if you placed it in global scope in the ...[more code] lines, the object would not be collected as it is still reachable).

Most of the time, you don't have to worry about explicit memory management in JavaScript, however it is important to know common cases where it does matter (see 4 common leaks).

As a practical example, in most front-end frameworks/libraries, it's important to destroy setIntervals created by short-lived components of your app (i.e. destroying a countdown clock's interval when that countdown clock has been removed from the DOM) as the closure in these intervals could prevent objects from being collected.



来源:https://stackoverflow.com/questions/48507237/javascript-new-keyword-and-memory-leaks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!