how to release closure's memory in javascript?

前端 未结 2 1590
名媛妹妹
名媛妹妹 2021-01-16 04:08

A closure:

function test() {
  var count = 0;

  return function() {
    count++;
  };
}

As we all know, the count won\'t rele

2条回答
  •  清酒与你
    2021-01-16 04:21

    closures is a massive source of memory leaks in JavaScript.

       function foo() {
        var count = 0;
        function do() {
         return count++;
        }
        return {
         do: do}
       } 
    

    Here foo() return the do function expression and do() have closure over th e count variable. We don't know when the returned do() expression will be called. So the garbage collector can't understand when to release the memory. So we need to manually release it after its usage.

提交回复
热议问题