What is a closure?

How do I define closures?

Let’s start with some code:

var name = 'ouda'
function fun() {
  console.log(name) // ouda
}

fun()
Copy the code

In the above code, we have a function fun and an external variable name. Fun refers to the external variable name, so we can consider the function fun and the variable name to form a closure.

So personally, a closure is the sum of a function and the variables outside the function that the function references.

Some people might wonder if we see closures that return values and are a function as a whole. It doesn’t actually mean that the whole thing is a closure, but this is the application of a closure to a function.

The application of closures in functions.

So the whole function that we saw, as I said, might look something like this:

Here the plus function and the number variable form a closure. Closures are nested inside the function Fun. This has the advantage of hiding the closure variables. It can be found that when we call fun externally, we cannot directly access number, but we can modify number through fun.

function fun() {
  var number = 1
  function plus() {
    number++
    return number
  }
  return plus
}

var func = fun()
console.log(func()) //2
console.log(func()) //3

Copy the code

The number variable, which cannot be accessed directly, is increased by 1 in a single call, which is the most effective protection against arbitrary changes in real development.

Discussion on closure memory leaks

As a matter of fact, I have looked through some materials and some discussions on this issue. I agree with the following statement:

Whoever said that has no idea what a memory leak is. A memory leak is when variables that you don’t need (or can’t access) still occupy memory space and can’t be reused.

The variable inside the closure is clearly the variable we need (lives), why is it a memory leak?

How did this rumor originate?

Because Internet explorer. There is a bug in IE, IE is still unable to retrieve variables referenced in closures after we use them.

This is an IE problem, not a closure problem. See this article by Masumi Seto

I won’t go into too much discussion here. After all, there are different ideas.