Question 48: what is closure?

Time:2021-9-23

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

After watching closures in JS advanced programming, I found that they can be described more specifically. This article will be updated later

Chestnuts

function foo() {
    var local = 1;
    function bar() {
        local++;
        return local;
    }
    return bar;
}

var func = foo();
console.log(func()); // 2

advantage

  1. You can read variables inside a function
  2. The variables inside the function remain in memory and are not destroyed

shortcoming

  1. If the closure is not used, it should be released in time, otherwise it will cause memory leakage

The content / inspiration of the article is drawn from the following content