2014-09-04 60 views
2

我是012,的新手,并试图了解与使用此Mozilla参考的对象相关的内存管理:MDN Memory Management了解JavaScript中的内存管理,Mozilla

我正在关注一个示例,但在理解引用时遇到问题。

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'?,那有一个对象的引用 - 哪个对象?

有人可以用实际的对象名称来重述上面的注释吗?

它可能会考虑作为汤匙喂养问题,但让我知道是否不值得问这个问题。我会删除它。

+0

对象没有名称;这点很重要。有引用对象的变量(或对象属性),或者没有。 – Pointy 2014-09-04 20:19:20

+0

JavaScript对象具有文字表示法。这些对象可以有其他对象作为它们的属性。 – 2014-09-04 20:20:04

回答

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.