【发布时间】:2011-04-14 19:04:25
【问题描述】:
我的直觉是,将代码块封装在匿名函数中是个好主意:
(function() {
var aVar;
aVar.func = function() { alert('ronk'); };
aVar.mem = 5;
})();
因为我不再需要aVar,所以我假设垃圾收集器会在aVar 超出范围时删除它。这是正确的吗?或者解释器是否足够聪明,可以看到我不再使用该变量并立即清理它?是否有任何理由(例如样式或可读性)我应该不以这种方式使用匿名函数?
另外,如果我给函数命名,像这样:
var operations = function() {
var aVar;
aVar.func = function() { alert('ronk'); };
aVar.mem = 5;
};
operations();
operations 是否一定会一直存在直到超出范围?或者解释器可以立即告诉它何时不再需要?
更好的例子
我还想澄清一下,我不一定要谈论全局范围。考虑一个看起来像
的块(function() {
var date = new Date(); // I want to keep this around indefinitely
// And even thought date is private, it will be accessible via this HTML node
// to other scripts.
document.getElementById('someNode').date = date;
// This function is private
function someFunction() {
var someFuncMember;
}
// I can still call this because I named it. someFunction remains available.
// It has a someFuncMember that is instantiated whenever someFunction is
// called, but then goes out of scope and is deleted.
someFunction();
// This function is anonymous, and its members should go out of scope and be
// deleted
(function() {
var member;
})(); // member is immediately deleted
// ...and the function is also deleted, right? Because I never assigned it to a
// variable. So for performance, this is preferrable to the someFunction
// example as long as I don't need to call the code again.
})();
我的假设和结论是否正确?每当我不打算重用一个块时,我不应该只将它封装在一个函数中,而是将它封装在一个匿名函数中,这样该函数就没有引用,并且在它被调用后被删除,对吧?
【问题讨论】:
-
只是好奇,有没有考虑内存泄漏?
标签: javascript garbage-collection scope anonymous-function