当前位置:网站首页>Master closures and consolidate basic skills
Master closures and consolidate basic skills
2022-07-28 13:59:00 【Maic】
Closures are everywhere in programs , Popular speaking
A closure is a combination of a function's reference to its surrounding state and binding it together, You can also understand it asA function is surrounded by referencesOr is itAn internal function can access the scope of an external function
Closure It is often taken in interviews , It is also an important point to understand the basic knowledge of a programmer , This article is written for Closure The understanding of the , Hope to think and help in the actual project .
Text begins ...
What is a closure
We can understand from the following points
- Closure is
A functionFor itsThe surrounding stateOfquoteAnd tied togetherCombine A functionByquoteSurroundAn internal functionAccess toExternal functionOfScope
Let's look at a picture and understand the above three sentences
The corresponding code is as follows
function A() {
var name = 'Maic',age = 0;
function B() {
console.log(name, age);
}
}
A();
// console.log(name) name is not defined
We noticed that in A Function , We created two internal private variables name、age, And we are A Function to create an internal function B, At this time in B Function , We will find that in the B It can be accessed internally The surrounding state ( Variable ), Which means in B Functions can be accessed internally External function Scope of action .
At this point you will find , Closure Is in the B As soon as the function is created , And there are right The state of being around With reference , So at this time Closure And that's what happened , in other words , Closure is a bridge , Can let B Function can break through Self scope visit external The variable of .
I don't know if you noticed , I am here A Internally defined variables , I can't access it from outside , That is to say, relatively A The outside of the ,A All internal variables are Private , stay A Variables defined , be relative to B in , You can also visit . because B Function can access A The variables in the , It depends on Closure This bridge .
Properties of closures
1. Create private variables
2. Extend the life cycle of variables
We know Closure Can cause memory leaks , Essentially, the created variables are always referenced in memory , When an ordinary function is called, it ends , Variables created inside the function will be destroyed .
But closures save references to their variables , Even if the external execution context is destroyed , But the lexical environment created in the closure is still there , Let's look at the following code for specific understanding .
function A() {
var name = 'Maic',age = 0;
function B() {
age++;
console.log(name, age);
}
return B
}
var b1 = A();
b1(); // 1
b1(); // 2
b1(); // 3
stay A Function returned in B, It actually returns a function , When we use var b1 = A() When declaring a variable , actually , Inside here B Not implemented yet , But in execution A() When the method is used , Returns a function , So we continue to carry out b1(), We try to call three times , We will find that the printed value is 1,2,3, This means that , Closure Extends the life cycle of variables , Because the value printed for the third time and the second time is the reference of the same value . A specific picture can be understood
When we use var b1 = A() when , actually , I have marked it with a blue box , stay b1 Inside we can see , Every execution b1, Actually, it is implemented Red Function of region , That is to say A Internally defined functions B, But every time I call b1, We all see reservations age References to , So you see age In turn 1,2,3, So it is confirmed Closures extend the life of variables , And closures are created Private variables You can reduce the use of global variables .
Usually we know to create as few global variables as possible , Because we don't know when to use this global variable , It will only be released when it is used . Closures also solve the problem of global variable naming conflicts , Because the private variables created , Can't be accessed externally , This will reduce Variable name The problem of pollution .
wait , There's another problem , What if I change the above code to the following ?
function A () {
var name = 'Maic',age = 0;
function B() {
age++;
console.log(name, age);
}
return B
}
A()(); // 1
A()(); // 1
// var b1 = A();
// b1();
// b1();
// b1();
// console.log(name)
You'll find that , I printed the same one twice 1, Why is that ? Have you noticed that we used var b1 = A() Declare a variable , In fact, this code is js The newly opened temporary storage space , because A The internal return is a function , Every time I call b1 when , It is actually the function returned by the call , Because there are references to closures inside the function , So always 1,2,3, But what I use here is A()(), We found that every time 1, Explain that when I call it for the second time, the internal age It has been redefined , And there is no reference to the last value , This means that , stay A() When called immediately , The variables referenced inside the closure have been released . because Closure There will also be flaws , Creating too many closures will cause serious memory consumption , Affects web page performance .
Application scenarios
Coriolis functionCallback functionCounter、Delay call ( Anti shake and throttling )
- Coriolis function
In fact, it is to split multiple parameters of a function into multiple function calls , The main purpose is Avoid calling functions with multiple same parameters , You can reuse the same function , The details can be understood with the following code
// Before coritization
function sum(a,b,c) {
return a+b+c
}
sum(1,2,3)
After the function is corized
function sum(a) {
return function(b) {
return function(c) {
return a+b+c
}
}
}
const a = sum(1);
const b = a(2);
const c = b(3);
console.log(c) // 6 or sum(1)(2)(3)
It still doesn't seem obvious , In specific business , You might write code like this
// Check a field according to regular rules
function regKey(reg, val) {
return reg.test(val)
}
var isPhone = regKey(/^1[3,5,7,8,9]\d{9}$/, 13754123124);
const isNumber = regKey(/\d/, 'test');
After changing to function coriolisation
function regKey(reg) {
return (val) => {
return reg.test(val)
}
}
const checkPhone = regKey(/^1[3,5,7,8,9]\d{9}$/);
const checkNum = regKey(/\d/);
const isPhone = checkPhone(13754123124) // true
const isNumber = checkNum(123); // true
We found that after the modification , It seems that after Kerry's transformation , Instead, there are more codes , But the readability and extensibility of the code are more friendly than before , This depends on special business functions , It is not necessary to use Coriolis function to deal with all businesses , The details depend on the situation , Here's just a simple example .
- Callback function
Callback function Used too much in business , See the following simple example for details , Write a paragraph for pseudo code to feel
const request = (params) => {
const response = {
code: 0,
success: ' success ',
data: []
};
return (callback) => {
callback(response);
}
}
const queryList = () => {
const getData = request({pageIndex:1, pageSize: 10});
getData((res) => {
console.log(res) // {code: 0, success: ' success ', data: []}
})
}
- Counter
This is very typical , For example, in a cycle
for (var i=0;i<10;i++) {
(function() {
var j = i;
setTimeout(() => {
console.log(j)
}, i* 1000)
})()
}
- Function throttling
Frequently triggered events , Call the function within a specified period of time
// Analog data request pseudocode
const fetchList = () => {}
let flag = false;
window.addEventListener('scroll', () => {
if (flag) {
return;
}
flag = true;
setTimeout(() => {
flag = false;
fetchList();
}, 500)
})
- Function anti shake
Use timer as buffer , When called the second time , Clear the last timer , Call the function again within the specified time
// Analog data request pseudocode
const fetchList = () => {}
const inputDom = document.getElementById('input');
let timer = null;
inputDom.oninput = function() {
if (!timer) {
clearTimeout(timer);
timer = setTimeout(() => {
fetchList();
}, 500)
}
}
The above cases are useful Closure , Closures are everywhere , It's just when we use it , We didn't find it .
summary
- ` Closure `[1] The concept of , Closure is
A functionFor itsThe surrounding stateOfquoteandbindingA combination together , Or is itA functionByquoteSurround , Or is itAn internal functionAccess toExternal functionScope of action - Properties of closures ,
Create private variablesandExtend the life cycle of variables - Application scenarios of closures ,
Coriolis function、Callback function、Timer、throttle / Shake proofetc. - An example of this article code example[2]
Last , Please give me a like , Looking at , forward , Collecting is learning , Welcome to the official account Web Technology academy , study hard , Day day up !
Reference material
[1] Closure : https://vue3js.cn/interview/JavaScript/closure.html#%E4%B8%80%E3%80%81%E6%98%AF%E4%BB%80%E4%B9%88
[2]code example: https://github.com/maicFir/lessonNote/tree/master/javascript/09-%E9%97%AD%E5%8C%85
边栏推荐
- 了解虚拟列表背后原理,轻松实现虚拟列表
- R语言ggplot2可视化:可视化散点图并为散点图中的数据点添加文本标签、使用ggrepel包的geom_text_repel函数避免数据点标签互相重叠(自定义指定字体类型font family)
- Intersectionobserver
- Debezium series: major changes and new features of 2.0.0.beta1
- POJ3275 Ranking the Cows题解
- 算法---不同路径(Kotlin)
- [C language] the difference between structure pointer and structure variable as formal parameters
- 国产API管理工具Eolink太好用了,打造高效的研发利器
- R language ggplot2 visualization: use the ggviolin function of ggpubr package to visualize violin diagrams, set the palette parameter, and customize the border colors of violin diagrams at different l
- 数据库系统原理与应用教程(058)—— MySQL 练习题(二):单选题
猜你喜欢

strcmp、strstr、memcpy、memmove的实现

面经整理,助力秋招,祝你称为offer收割机

Chapter 6 support vector machine

Security assurance is based on software life cycle -istio authorization mechanism

word打字时后面的字会消失是什么原因?如何解决?

对“Image Denoising Using an Improved Generative Adversarial Network with Wasserstein Distance“的理解

SLAM论文合集

Istio IV fault injection and link tracking

30 day question brushing plan (III)

SQL daily practice (Niuke new question bank) - day 4: advanced operators
随机推荐
《机器学习》(周志华) 第6章 支持向量 学习心得 笔记
【架构】评分较高的三本微服务书籍的阅读笔记
JWT 登录认证 + Token 自动续期方案,写得太好了!
Understanding of stack and practical application scenarios
Product Manager: job responsibility table
R语言使用lm函数构建线性回归模型、使用subset函数指定对于数据集的子集构建回归模型(使用floor函数和length函数选择数据前部分构建回归模型)
Socket类关于TCP字符流编程的理解学习
Analyzing the principle of DNS resolution in kubernetes cluster
SQL daily practice (Niuke new question bank) - day 4: advanced operators
安全保障基于软件全生命周期-NetworkPolicy应用
30天刷题计划(二)
Qt5开发从入门到精通——第一篇概述
How to check if the interface cannot be adjusted? I didn't expect that the old bird of the 10-year test was planted on this interview question
Strict mode -- let and const -- arrow function -- Deconstruction assignment -- string template symbol -- set and map -- generator function
R language ggplot2 visualization: visualize the scatter diagram and add text labels to the data points in the scatter diagram, using geom of ggrep package_ text_ The rep function avoids overlapping da
Chapter 6 support vector machine
【LVGL事件(Events)】事件在不同组件上的应用(一)
Security assurance is based on software life cycle -istio authorization mechanism
Record a fake login of cookie
30天刷题计划(三)