javascript - 了解 JavaScript 中的内存管理,Mozilla

标签 javascript object memory-management garbage-collection

我是 JavaScript 的新手,正在尝试使用此 Mozilla 引用了解与对象相关的内存管理:MDN Memory Management .

我在看一个例子,但在理解引用文献时遇到问题。

var o = { 
  a: {
    b:2
  }
}; 
// 2 objects are created. One is referenced by the other as one of its property.
// The other is referenced by virtue of being assigned to the 'o' variable.
// Obviously, none can be garbage-collected

   var o2 = o; // the 'o2' variable is the second thing that 
                // has a reference to the object
    o = 1;      // now, the object that was originally in 'o' has a unique reference
                // embodied by the 'o2' variable

    var oa = o2.a; // reference to 'a' property of the object.
                   // This object has now 2 references: one as a property, 
                   // the other as the 'oa' variable

    o2 = "yo"; // The object that was originally in 'o' has now zero
               // references to it. It can be garbage-collected.
               // However what was its 'a' property is still referenced by 
               // the 'oa' variable, so it cannot be free'd

    oa = null; // what was the 'a' property of the object originally in o 
               // has zero references to it. It can be garbage collected.

我对这个对象一个被另一个引用、创建了 2 个对象 - 为了什么? 'o' & 'a'?,它引用了对象 - 哪个对象?

有人可以用实际的对象名称改写上面的注释吗?

它可能被视为一个填鸭式问题,但如果不值得问这个问题,请告诉我。我会删除它。

最佳答案

这是一个有点糟糕的解释。我给你一个粗略的版本。

var o = { 
  a: {
    b:2
  }
}; 
// 2 objects are created. One (the value of the property named "a")
// is referenced by the other (the value of the variable named "o")
// as its property.
// The other (the value of the variable named "o")
// is referenced by virtue of being assigned to the 'o' variable.
// Obviously (maybe to the author...), none can be garbage-collected

var o2 = o; // the 'o2' variable now also
            // has a reference to the object (the value of the variable "o")

o = 1;      // "o" now refers to something else and "o2" is the only variable
            // referring to the original "o" object.

var oa = o2.a; // reference to the 'a' property of the "o2" object.

o2 = "yo"; // The object that was originally in 'o' has now zero
           // references to it, but
           // the object's 'a' property is still referenced by 
           // the 'oa' variable, so the "o2" object cannot yet
           // be GC'ed.

oa = null; // The object now has zero references to it, so it can be
           // garbage collected.

关于javascript - 了解 JavaScript 中的内存管理,Mozilla,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25674269/

相关文章:

objective-c - 为什么不简单地使用 [NSDate 日期]?

javascript - 如何将带有对象的字典转换为 geoJson?

qt - 我是否需要显式删除顶级窗口以避免 Qt 中的内存泄漏?

javascript - Ajax.Begin 正在使用 MVC 5 重新提交整个页面

Javascript 返回并添加到 url 的查询

arrays - 在 swift 中按 array.count 对对象进行排序

Android memoryInfo 值

iphone - @property setter 泄漏

javascript - SAPUI5 - 更新 View

javascript - 语义 UI 进度条是否可以在没有 javascript 的情况下工作?