What is a closure?

A closure is a function that can read variables outside a function or inside another function. Because in the Javascript language, only subfunctions inside functions can read local variables, closures can be understood simply as “functions defined inside a function.”

What’s in the closure?

① Prevent variables from being globally polluted (variable privatization)

② Access variables outside the function

What is a memory leak

First, you need to understand the browser’s own memory reclamation mechanism. Each browser has its own collection mechanism that recycles allocated memory when it is not in use. The root cause of a memory leak is that your code allocates some “stubborn” memory that the browser can’t reclaim. If the “stubborn” memory continues to be allocated, it will run out of memory and leak.

Because of the closure is to be able to access external function variables of a function, and function is an object must be stored in memory, so the function in the context of all variables also need to be kept in memory, so as not to be recycled, if once the circular reference or create closure, will occupy a lot of memory, may cause a memory leak

How to avoid memory leaks caused by closures:

1. Before exiting the function, delete all unused local variables, which can be assigned to null

// This code causes memory leaks
    window.onload = function(){
        var el = document.getElementById("id");
        el.onclick = function(){ alert(el.id); }}// The solution is as follows
    window.onload = function(){
        var el = document.getElementById("id");
        var id = el.id; // Remove circular references
        el.onclick = function(){
            alert(id); 
        }
        el = null; // Clear live objects from external functions referenced by the closure
    }
Copy the code

Considerations for using closures

(1) Because the closure will make the variables in the function are saved in memory, which consumes a lot of memory, so we should not abuse the closure, otherwise it will cause performance problems of the web page, and may lead to memory leakage in IE. The solution is to remove all unused local variables before exiting the function.

(2) The closure changes the values of the variables inside the parent function outside the parent function. So, if you use a parent function as an object, a closure as its Public Method, and internal variables as its private values, be careful not to arbitrarily change the values of the parent function’s internal variables.