Is it good practice to set variables to null when they are no longer needed?

前端 未结 4 1985
一生所求
一生所求 2020-12-05 09:32

I have seen javascript values set to null at the end of a function. Is this done to reduce memory usage or just to prevent accidental u

4条回答
  •  孤街浪徒
    2020-12-05 10:25

    It wouldn't make any difference setting a local variable to null at the end of the function because it would be removed from the stack when it returns anyway.

    However, inside of a closure, the variable will not be deallocated.

    var fn = function() {
    
       var local = 0;
    
       return function() {
          console.log(++local);
       }
    
    }
    
    var returned = fn();
    
    returned(); // 1
    returned(); // 2
    

    jsFiddle.

    When the inner function is returned, the outer variable's scope will live on, accessible to the returned inner function.

提交回复
热议问题