JS closure learning notes
JavaScript closure, I believe that the preschool partners are familiar with the word, but when asked what is a closure, but can only answer a little concept related, so today I write a study day to sort out some of the knowledge of closed packages learned on the Internet.
1. What are closures
First, we need to understand that variables in JS are divided into global variables and local variables. A function can access variables defined inside the function (local variables) and global variables, but cannot access variables inside the function. When a function is nested inside the function, the inside function can also access variables defined outside the function. This is one of the prerequisites for understanding closures. So what exactly is a closure? I’ve looked at the various concepts of closures that are abstract and varied. However, closures have two concepts:
- Function nested function;
- Internal functions can access variables of external functions;
What is the closure in Zhihu’s “Question of the Day” JS? One of the best answers in ‘mentions this concept:
The sum of the “function” and the “variables accessible within the function” (also known as the environment) is a closure.
To summarize this in my own words, a function is a closure that has a function nested within itself, and its subfunctions can access variables and parameters in the external function. So much for the closure concept of the interview question. This is a simple closure:
var add = (function () {
var counter = 0;
return function () {return counter += 1; }}) (); add();Copy the code
2. What do closures do
So what do closures do in our development environment? When do we need closures? As we all know, in normal cases, when we call a function, the variables in it are immediately recycled. In a closure, however, the variable is not destroyed because it is still referenced by the function inside the function. Also, global variables are compared to variables inside a function. Global variables are universally callable and therefore easy to change; However, a variable inside a function is not accessible from the outside, so we can only call the variable through the function inside the closure, and as mentioned earlier, the variable is not destroyed, so we can call it again next time. Thus, we can roughly summarize what closures do: we can use closures when we want a variable to change only through a function call, and we want the variable to be saved. Again, because this variable is what we want it to hold, closures don’t cause memory leaks. So these are some study notes on closures. Three common questions that closures ask in interviews: What is a closure? What do closures do? Do closures cause memory leaks? Now we have a certain understanding. New content will continue to improve the follow-up oh!