以下是我所拥有的一些代码的非常简化(有点难看)的版本。当我在代码执行之前和之后比较Chrome中的堆snapsnots时,不会收集someObject和subObjectCollection。这让我感到困惑,因为看起来泄漏是由循环引用引起的,这对于Chrome中的v8垃圾收集器来说应该不是问题。我没看到这个导致它泄漏的代码?如何重构以便清理这些对象? JSFiddle
var someObject = function (name) {
var _subObjects = [];
this.name = name;
var parent;
this.getObjects = function () {
return _subObjects;
}
this.addObject = function (o) {
_subObjects[_subObjects.length] = o;
o.setParent(this);
}
this.setParent = function (o) {
parent = o;
}
this.getParent = function () {
return parent;
}
}
var subObjectCollection = function (name) {
var parent;
this.name = name;
this.list = [];
this.setParent = function (o) {
parent = o;
}
this.getParent = function () {
return parent;
}
}
var obj1 = new someObject("Top Level Object");
var objCollection = new subObjectCollection("Object Collection");
obj1.addObject(objCollection);
var obj2 = new someObject("Child Object");
obj2.setParent(obj1);
obj1.getObjects()[0].list[0] = obj2;