我的直覺是,它的封裝在匿名函數的代碼塊這樣一個好主意:我應該在匿名JavaScript函數中封裝功能塊嗎?
(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.
})();
我的假設和結論在那裏是正確的嗎?每當我不打算重用塊時,我不應該只將它封裝在一個函數中,而是將它封裝在一個匿名函數中,以便該函數沒有引用並在調用它後被刪除,對嗎?
只是好奇,有沒有考慮內存泄漏? – jebberwocky 2010-09-20 17:03:59