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

标签 javascript garbage-collection

给定

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/

相关文章:

javascript - Google Places API 字段过滤器不适用

java - 使用 Wea​​kHashMap 减少内存使用

.net - 有时是否必须使用 COM 对象显式调用 gc.collect

android - 我如何优化此代码以减少垃圾收集?

javascript - 将 JSON 响应状态发布到服务器

Javascript 类在 Chrome 上运行良好,但在 Edge 上运行不佳。为什么?

javascript - 在 A 依赖于 B、B 依赖于 C 的情况下,并行处理 A、B 和 C 的完美工作流程是什么?

javascript - $(this) 引用扩展 JQuery 方法中的第一个选择器元素

c# - 为什么其他语言没有类似 Java 垃圾收集器的自动垃圾收集?

logging - GOGCTRACE 和采集时间