【问题标题】:Understanding Memory Management in JavaScript, Mozilla了解 JavaScript、Mozilla 中的内存管理
【发布时间】:2014-09-04 20:15:36
【问题描述】:

我是 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'?,表示对对象的引用 - 哪个对象?

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

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

【问题讨论】:

  • 对象没有名字;这就是重点。要么有变量(或对象属性)引用了一个对象,要么没有。
  • JavaScript 有对象的文字符号。这些对象可以有其他对象作为它们的属性。

标签: javascript object memory-management garbage-collection


【解决方案1】:

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

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    相关资源
    最近更新 更多