简体   繁体   English

此Javascript是否会导致内存泄漏?

[英]Does this Javascript cause a memory leak?

Notice in the following code, the child gets a reference to its parent. 请注意,在以下代码中,子级获得对其父级的引用。 What happens when the original reference to parent is set to null? 将对父对象的原始引用设置为null时会发生什么? Does the parent stay around since there still is an active reference from the child? 父母是否会留下来,因为仍然有孩子的积极推荐?

Javascript Java脚本

var parent = function() {
  var self = this;
  self.runme = function() {
    document.getElementById('output').innerText = 'run me';
  }

  self.child = new child(self);

  return self;
}
var child = function(parent) {
  var self = this;
  var parent = parent;
  self.event = function() {
    parent.runme();
  }
}
var p = new parent();
p.child.event();
p = null;

HTML HTML

<div id="output">
  old value
</div>

FIDDLE https://jsfiddle.net/jeljeljel/8fvy5r4f/ FIDDLE https://jsfiddle.net/jeljeljel/8fvy5r4f/

var p = new parent();
p.child.event();
p = null;

Eventually both parent and child will be garbage collected because neither parent nor child will be "reachable" anymore. 最终,父母和孩子都将被垃圾回收,因为父母和孩子都不再是“可到达的”。 There's no memory leak here. 这里没有内存泄漏。 That's assuming you are dealing with a modern JavaScript interpreter. 假设您正在使用现代JavaScript解释器。

It shouldn't because most garbage collectors are based on the idea of reachability . 不应这样,因为大多数垃圾收集器都是基于可到达的思想。 Basically, if the object isn't reachable from the root(s) of the graph then it can be safely collected. 基本上,如果从图的根部无法访问该对象,则可以安全地收集该对象。 After initialization you create a graph like this: 初始化后,您将创建一个如下图:

root -> parent <-> child

Then after p = null you get this: 然后在p = null ,得到以下结果:

root X parent <-> child

Since neither parent nor it's dependents are reachable, they can all be safely collected. 由于parent及其亲属都无法联系到,因此可以安全地收集他们。

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

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