Today is word reasoning

In JavaScript, whenever a function is created, the closure is created at the same time that the function is created.

All functions in JS have a closure.

A closure is a function that has access to a variable in the scope of another function. A common way to create closures is to create another function inside one function.

Let’s see if these conclusions are true

  • Closures are functions

    A closure is a function that has access to variables in the scope of another function

  • Functions are closures

    Because every time a function is created, the closure is created at the same time that the function is created. (By creating a function, you have both a function and a closure that can access variables in another function’s scope.)

    And because closures are functions.

    So functions are closures, right?

To prove that a function is a closure?

We have two scenarios for creating functions in JS, one is global, and one is inside a function (common methods will be skipped).

We create a function globally, and that function is a closure?

Come to the conclusionfunA function is a closure because:

  • Access to another function scope (global scope)
  • It’s a function

I had no idea what to do, and finally turned to the JavaScript Definitive Guide and saw this:

Technically speaking, all JavaScript functions are closures: they’re all objects, and they’re all associated with a scope chain.

So closures are functions, functions are closures, and there’s nothing wrong with either conclusion.

Closures are not the only closures we think of as closures:

function outside(){
  const str = 'haha';
  return function inside(params) {
    console.log(str); // The inner function accesses the scope of the outer function (also known as closure)
  }
}
outside()(); // External accesses the internal variables of outside
Copy the code

In fact, this is a closure in practice, and it’s a closure that we usually use smartly. That is, the ability to access internal variables of a function externally. The reason we can access the inner variable is because the function has an nested function and the nested function has a reference to the parent scope, which forms a practical closure.

Looking at the code above, theoretically outside and inside are closures, but in practice we are used to calling inside closures.

To summarize

The theory: closures are functions, and functions are closures.

In practice: a closure is an embedded function with a reference to the parent scope.

The understanding of the concept is usually more problems, but also hope that we help point out!