Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Writing in the front

I saw an old knowledge sharing closure when I looked at the interview questions these days, so I made a note

closure

What is a closure? A function that can access free variables, divided into a code part and an environment part.

All free variable lookups in js are found in the parent scope where the function is defined, not where it is executed

Closure representation in JS

Functions are passed as arguments

const b = 200;
function print (fn) {
    const b = 100;
    fn();
}
function foo () {
    console.log(b);
}
print(foo) // 200
Copy the code

The function is returned as the return value

function foo () { const a = 100; return function () { console.log(a) } } const a = 200; const fn = foo(); fn(); / / 100Copy the code

Sharing a closure

If there are two or more functions in a function, when one of them uses the external variable A, then a is stored even if the other functions do not.

Example:

function foo () { const a = 100; var func = function () { console.log(a) } return function () { ... }}Copy the code

In function foo, there is a function scoped variable, a, called in func, which is then stored in the returned anonymous function. Although this is not noticeable, it can cause a serious memory leak that is not easily noticed.

Solution: Simply remove the useless func.

Write in the last

This article is very simple, closure is a platitude, usually simple business I try to avoid using, so the understanding is not very deep.

I hope my article can give you a part of the inspiration and help, if there is any deficiency or wrong place, welcome readers to comment and leave a message

Of course, if this article is of any help to you, please like and retweet it. Thank you 🙏

GitHub article collection address