- The true understanding of JS closures from partial to comprehensive will never be forgotten!
Part I (Partial Understanding)
When the interviewer asked me what a closure is and what it actually does, MY initial response was:
- Part I (Partial Understanding)
From the original partial understanding
What is a closure: access to local variables outside a function;
Because I came from the back end and turned to the front end based on my understanding of the back end language, I used to think that the purpose of closures was simply something like common methods and private methods on the back end
The module pattern can be written to mimic the back-end language’s private and public methods, such as:
var person = (function Moudels() {
let name= "test";
function getTest() {
console.log(name);
}
return function getName() {
console.log(name);
}
return function getAge() {
console.log(name+'30');
}
})();
person.getName();
person.getAge();
Copy the code
Two external methods getName and getAge are exposed for external access to the internal variables Name and getTest are private methods
Part 2 (Overall Understanding)
When the interviewer asks me what a closure is and what its functions and uses are, my answer now is: /**
- Part 2 (Overall Understanding)
Deeper understanding: Know why closures exist what are closures and what scenarios use closures
What is a closure you have to know why there is a closure just like what is kung pao chicken you have to know why is it called Kung pao chicken
Begin to delve deeper into the previous partial understanding:
For example:
function f1() {
var a = 10;
function f2() {
alert(a);
}
f2()
}
f1();// Access the local variable name
Copy the code
Does this code count as a closure? Why is that?
The external getName can access the internal variable name. The external getName can access the internal variable name.
function f1() {
var name = 'test';
return name;
}
f1();// You can also access the local variable name; So the external function can also access the internal name variable
Copy the code
Obviously neither of these are closures
So start to really understand closures closures are not for nothing there must be a reason
Key points:
Closures: The first is the previously mentioned ability to read variables inside a function;
Another function is to keep these variables in memory all the time; No longer destroys and frees after function calls
Conclusion 1: Local variables cannot be shared and stored for a long time; Global variables can cause variable pollution, and we want to have a mechanism to preserve variables for a long time without causing global variable pollution
Conclusion 2: The emergence of closures: a function returns an inner function; And a reference to a local variable produces a closure
// Closure:
function f1() {
var a = 10;
function f2() {
a++;
console.log(a)
}
return f2;
};
var f = f1();
f();
// When f is not called, the state of a is saved and will not be freed after f1() is executed
// Simplify
function f1(){
var a =10;
return function() {
a++;
console.log(a); }}var f= f1();
f();
Copy the code
To impress take a look at the control day output:
FIG. 1
Figure 2
Figure 2 shows that each function stores the state of local variables of the corresponding function
Purpose Summary: A supplement to the public and private methods of the Moudel pattern, following the purpose of part 1
I was a little confused when I was learning the Moudel pattern that if you just expose public methods and variables there are a lot of different ways to do that
For example, return an object containing the following methods or variables that you want to publish:
function Person() {
var name='test';
function getName() {
console.log(name);
}
function getAge() {
console.log(name + '30');
}
function getHeight() {
console.log('Two metres tall');
}
return {
name:getName(),
aget:getAge()
}
}
Copy the code
Or I could just define the object and publish it
var Person = {
name:' '.age:' '.getName:function() { console.log(this.name)},
getAge:function() {console.log(this.age)};
}
export default Person;
Copy the code
Summary: [Can achieve some real use of saving state]
Example 1: Use immediate functions in closures
Execute functions immediately within closures
1. Execute functions immediately to save state with closures.
Consider the closure example from the previous section:
function makeClosures(i){
var i = i;
return function(){
console.log(i); }}for (var i=1; i<=5; i++) {
setTimeout(makeClosures(i),i*1000);
}
/ / 1
/ / 2
/ / 3
/ / 4
/ / 5
// Now, let's simplify it with the immediate execution function:
for (var i=1; i<=5; i++) {
setTimeout((function(i){
return function(){
console.log(i);
}
})(i),i*1000);
}
Copy the code
Example 2: Using the Moudle pattern in combination with closure modularization
Now let’s walk through the process of modular development with a simple example. What this example is trying to do is that every second, the background color of the body switches between a fixed set of three colors as the number increases.
(1) First create a module dedicated to managing global state. This module has a private variable that holds all the state values and provides methods to access and set this private variable. The code is as follows:
var module_status = (function() {
var status = {
number: 0.color: null
}
var get = function(prop) {
return status[prop];
}
var set = function(prop,value) {
status[prop] = value;
}
return {
get,
set
}
})();
Copy the code
Create a module that is responsible for changing the color of the body background.
var module_color = (function() {
// Pretend to do step 2 import modules in this way
// Similar to import state from 'module_status';
var state = module_status;
var colors = ['yellow'.'#ccc'.'red'];
function render() {
var color = colors[state.get('number') % 3];
document.body.style.backgroundColor = color;
}
return {
render
}
})();
Copy the code