问题
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 setInterval
s 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