我是 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/