我认为将代码块封装在匿名函数中是一个好主意,像这样:
(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.
})();
我的假设和结论是否正确?每当我不打算重用一个代码块时,我不仅应该将其封装在一个函数中,而且还应该将其封装在匿名函数中,这样函数就没有引用并且在调用后被删除,对吗?