tdoakiiii
tdoakiiii

Reputation: 372

What happens to an object created and stored in a function in Javascript?

Given

function Foo(){
   this.name = "foo"
}

Foo.prototype.hello = function(){
   alert("Hello");
}

function bar(){
  var foo = new Foo();
  foo.hello();
}

What will happen to variable foo? Will it get garbage collected?

Upvotes: 0

Views: 39

Answers (1)

PaulShovan
PaulShovan

Reputation: 2134

Many types of algorithm are used for garbage collection... according to MDN . In the above case, foo's scope is only inside bar. So, it will be garbage collected as soon as the function bar returns.

Reference-counting garbage collection

This is the most naive garbage collection algorithm. This algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it". An object is considered garbage collectable if there is zero reference pointing at this object.

Mark-and-sweep algorithm

This algorithm reduces the definition of "an object is not needed anymore" to "an object is unreachable".

This algorithm assumes the knowledge of a set of objects called roots (In JavaScript, the root is the global object). Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

foo is satisfying both of the algorithms to be garbage collected

Upvotes: 1

Related Questions