【发布时间】:2012-12-28 19:39:15
【问题描述】:
一段时间以来,我一直在使用两个版本的 JavaScript 模式,我从 Addy Osmani 那里学到了模块模式。 view it here
此模式的第一个版本使用对象字面量:
var x = {
b: function() {
return 'text';
},
c: function() {
var h = this.b();
h += ' for reading';
}
}
alert(x.b()) // alerts text.
而其他版本使用自执行功能:
var y = (function() {
var first = 'some value';
var second = 'some other value';
function concat() {
return first += ' '+second;
}
return {
setNewValue: function(userValue) {
first = userValue;
},
showNewVal: function() {
alert(concat());
}
}
})();
y.setNewValue('something else');
y.showNewVal();
鉴于上述示例,这两种模式中的任何一种(不考虑任何事件侦听器)是否对垃圾回收友好(鉴于它们引用自身的方式)?
【问题讨论】:
-
我想是的。只要你没有任何指向这些对象的东西,它们就会有资格进行 gc(包括闭包)。
-
@bfavaretto 第一个会(当我使用它时)通常会像“this.c() 或 this.b()”一样引用它自己,可以自我引用防止主对象成为 GC会吗?
-
我不是专家,但我不这么认为(尤其是因为
this是在 js 中的调用时间确定的)。
标签: javascript memory-management memory-leaks garbage-collection