John Livermore
John Livermore

Reputation: 31343

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? Does the parent stay around since there still is an active reference from the child?

Javascript

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

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

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

Upvotes: 0

Views: 125

Answers (2)

Mike Cluck
Mike Cluck

Reputation: 32521

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:

root X parent <-> child

Since neither parent nor it's dependents are reachable, they can all be safely collected.

Upvotes: 1

freakish
freakish

Reputation: 56587

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.

Upvotes: 2

Related Questions