var person = {
name: 'John'
};
function Pet1(person) {
var owner = person.name;
this.showOwner = function() {
alert(owner);
}
}
function Pet2(person) {
this.showOwner = function() {
alert(person.name);
}
}
var pets = [new Pet1(person), new Pet2(person)];
...
pets.splice(0, 1);
pets.splice(0, 1);
当 Pet1 和 Pet2 超出范围或没有更多引用时,上面的代码阻止 JS GC 不收集 Pet1 和 Pet2 的实例。我知道的是 Pet2 但你不认为 Pet1 也可以防止 JS GC 吗?
最佳答案
关于您评论中的问题:
will the person (it's global in this case) variable prevent instances of Pet1 and Pet2 to be garbage collected (if out of scope and no more references)
不,为什么要这样? person
不引用 Pet 实例,相反。一旦您从 pets
数组中删除了对 Pet 实例的引用,就没有什么可以阻止 GC 收集它们(假设您的“...
”代码没有创建对 pets[0]
或 pets[1]
的其他引用)。
关于javascript - 参数是否会使 JavaScript GC 无法收集对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15446841/