给定
function Foo(){
this.name = "foo"
}
Foo.prototype.hello = function(){
alert("Hello");
}
function bar(){
var foo = new Foo();
foo.hello();
}
变量 foo 会发生什么?它会被垃圾收集吗?
最佳答案
许多类型的算法用于垃圾收集...根据 MDN 。在上面的例子中,foo
的作用域仅在bar
内部。因此,一旦函数 bar
返回,它就会被垃圾回收。
引用计数垃圾回收
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
满足垃圾收集的两种算法
关于javascript - 在 Javascript 函数中创建和存储的对象会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31142463/