Looking back at the core concepts in JavaScript a year later, closures are a perennial topic of conversation in both job interviews and technical conversations. I remember when I first started working on the front end almost four years ago, I was always confused by the concept of closures. Every time I read an article about closures, I thought I understood it, and then when I was asked “What is a closure?” I couldn’t convince myself. I don’t know. I believe there are some students and I have the same feeling, here in the article let’s simply exchange what is a closure.
WHAT is a closure
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, A closure gives you access to an outer function’s scope from an inner function. closures are created every time a function is created, at function creation time.
Simply put, closures are a combination of functions and the lexical environment in which they are declared. The environment contains any local variables that were scoped when the closure was created. A closure is a combination that contains a function and a lexical environment around that function
For example, what is the final output of the following example?
for( var i = 0; i < 3; i++ ) { setTimeout(() => { console.log( i ); }}, 1000)Copy the code
I’m sure many of you know the answer to this question, and the answer is not 0,1,2, but 2,2,2
How does the above code adjust to achieve the desired output? The answer is to create mutually independent closures, in other words to change and rebuild a scoped/lexical environment around the setTimeout function. Here are two ways to do this.
For (var I = 0; i < 3; I + +) {(function (j) {setTimeout (() = > {the console. The log (j)}, 1000)}) (I)} / / method 2 es6 for (let I = 0; i < 3; i ++){ setTimeout(()=>{ console.log(i) },1000) }Copy the code
Classic test
function fun(n, o) { console.log(o); return { fun: function(m) { return fun(m, n); }}; } // var a = fun(0); a.fun(1); a.fun(2); a.fun(3); // Output?? // var b = fun(0).fun(1).fun(2).fun(3) // var c = fun(0).fun(1); c.fun(2); c.fun(3); // Output??Copy the code
The correct answer
// Undefined 0 0 0 // undefined 0 1 2 // undefined 0 1 1 1Copy the code
conclusion
Closures are everywhere. Javascript is a function-first object-oriented language. How to correctly understand and analyze the lexical environment or Scope of the current function is the key to understand closures.
I hope you can give me more feedback. If you think this article is good, please give a like thanks 😄 happy coding.