在 Javascript 的函数中创建和存储的对象会发生什么情况?

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

给出

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

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

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

变量 foo 会发生什么变化?它会收集垃圾吗?

许多类型的算法用于垃圾收集...根据 MDN 。在上面的例子中,foo 的范围仅在 bar 内。因此,一旦函数 bar returns.

就会被垃圾回收

引用计数垃圾回收

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.

标记清除算法

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 满足两种垃圾收集算法