当前位置:网站首页>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
边栏推荐
- Qt5 development from introduction to mastery -- the first overview
- 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
- Qt5开发从入门到精通——第一篇概述
- Deploy application delivery services in kubernetes (Part 1)
- Strict mode -- let and const -- arrow function -- Deconstruction assignment -- string template symbol -- set and map -- generator function
- SQL每日一练(牛客新题库)——第4天:高级操作符
- 30 day question brushing plan (IV)
- 30天刷题计划(二)
- Tutorial on the principle and application of database system (062) -- MySQL exercise questions: operation questions 32-38 (6)
- DXF reading and writing: align the calculation of the position of the dimension text in the middle and above
猜你喜欢

《机器学习》(周志华) 第6章 支持向量 学习心得 笔记

多线程与高并发(三)—— 源码解析 AQS 原理

第六章 支持向量机

The strongest distributed locking tool: redisson

SAP ui5 fileuploader control realizes local file upload, and trial version of cross domain access error encountered when receiving server-side response

Org.apache.ibatis.exceptions.toomanyresultsexception

【LVGL事件(Events)】事件在不同组件上的应用(一)

30 day question brushing plan (III)

记一次COOKIE的伪造登录

30天刷题计划(三)
随机推荐
SAP UI5 FileUploader 控件实现本地文件上传,接收服务器端的响应时遇到跨域访问错误的试读版
浅谈WebSocket
R语言ggplot2可视化:使用ggpubr包的ggviolin函数可视化小提琴图、设置palette参数自定义不同水平小提琴图的边框颜色
Dojnoip201708 cheese solution
es6你用过哪些惊艳的写法
Tutorial on the principle and application of database system (059) -- MySQL exercise questions: operation questions 1-10 (III)
POJ3259虫洞题解
Denial of service DDoS Attacks
Security assurance is based on software life cycle -istio authorization mechanism
Deploy application delivery services in kubernetes (Part 1)
url相关知识点
My friend sent me some interview questions
Continuous (integration -- & gt; delivery -- & gt; deployment)
[Architecture] reading notes of three micro service books with high scores
DXF reading and writing: align the calculation of the position of the dimension text in the middle and above
Long closed period private placement products reappearance industry insiders have different views
长封闭期私募产品再现 业内人士看法各异
面经整理,助力秋招,祝你称为offer收割机
POJ1860货币兑换题解
Product Manager: job responsibility table