簡體   English   中英

Javascript 關閉和 memory 問題

[英]Javascript closure and memory issues

//Following function add new table entry to table
//and return interface which has function which uses closure to access and update the table
var _newRow  = (function(){
    var _interface = {
        updateName: null,
        updateProgress: null,
        actionLinkButton : null,//<a> tag used for user aciton to perform on UI like delete, hide, show etc.
        ..
        ..
        ..
    };
    var tr = createTr();    
    var tdName = createTd();
    _inteface.updateName = function(newName){
        tdName.innerHTML = newName;
    }
    ..
    ..
    ..
    ..
    ..  
    return _interface;
})(tblObject);

//maintaining the array of all the rows as per row number
rowArray[rowNo] = _newRow;
..
..
//using the row array to update the entries
rowArray[rowNo].updateProgress('read');

以上是我用來更新客戶端上動態添加的行的模式。 我所做的是在向表中添加行時創建_interface,將其返回並按行號存儲。

但是為此,我使用了閉包意味着許多活動對象。 我想知道這是正確的方法嗎? 有沒有更好的方法呢? 我可以使用哪些分析工具來了解這段代碼使用了多少內存? 我如何確保在不需要時正確清除關閉?

JavaScript 有一個垃圾收集器,它將收集流浪對象並自動為您釋放它們。 沒有辦法控制何時或如何。

什么可能會阻止對象/閉包被垃圾收集是當你有全局可訪問的對象引用具有詞法 scope 的函數時。 確保分離所有不使用的值(例如,從 DOM 中刪除它們)。 如果您確定無法訪問這些值,它們最終將被垃圾收集。

要識別 memory 泄漏,重要的是不要過早優化,您可以監控 web 瀏覽器的 memory 使用情況。 如果它在那里不明顯,那么你可能不需要擔心它。 您可能想在您的應用程序中模擬很多操作,以查看應用程序運行很長時間后 state 可能會是什么樣子。

但一般來說,不用擔心 memory 的使用。 根據我的經驗,這很少是一個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM