current position:Home>JS function scope, closure, let, const
JS function scope, closure, let, const
2021-08-27 06:10:55 【Upwind boy】
What is a closure ?
simply , Closure is to include a function in a function , Internal functions have access to variables declared by external functions ; Closure involves function scope 、 Memory mechanism 、 Knowledge about function and chain
1、 Function scope
The so-called function scope is , Declare a function , Create a private scope in memory —— An enclosed space
Function fn(){
var a = 11;
}
fn();
Copy code
Beyond this scope, you will no longer access this variable .
2、 Memory recovery mechanism
The so-called memory recycling mechanism is that the system automatically recycles and cleans up the memory that is not needed , Make room for other programs to use .
Scope chain
function fn(){
var a =234;
return function(){
console.log(a);
}
}
Copy code
The scope chain is in the scope of a function , Function which scope of the name to execute first , If there is no definition, keep looking up , Until you find the global scope
The function of closures
The function of closures is simply to protect and preserve .
- Protection :
Store variables in a private scope , Avoid conflicts because of the same name 2、 Preservation function : Use the tab to save data
let and const The role of 【 important 】
let and const Its function is as follows :
-
It is forbidden to repeat the statement
-
Supports block level scopes
-
Control modification
contrary , use var
Declared variables : Can be repeated 、 There is no block-level scope 、 It can't be limited .
for Examples of cycles 【 Classic case 】
Code 1、 Let's first look at the following code :( use var Defining variables i)
<!DOCTYPE html>
<html lang="">
<head>
<meta />
<meta />
<meta />
<title>Document</title>
</head>
<body>
<input type="button" value="aa" />
<input type="button" value="bb" />
<input type="button" value="cc" />
<input type="button" value="dd" />
<script> var myBtn = document.getElementsByTagName("input"); for (var i = 0; i < myBtn.length; i++) { myBtn[i].onclick = function() { alert(i); }; } </script>
</body>
</html>
Copy code
The operation effect in the above code is as follows :
You may be surprised , Why click any button , The pop-up content is 4 Well ? This is because , We use it var Variables defined i, Is declared at the global scope . In the whole code , There is only one variable from beginning to end . Before we hit the button , Variable i Has been cycled to 4 了 .
in other words , above for loop , Equivalent to the following code :
var i = 0;
myBtn[0].onclick = function() {
alert(i);
};
i++;
myBtn[1].onclick = function() {
alert(i);
};
i++;
myBtn[2].onclick = function() {
alert(i);
};
i++;
myBtn[3].onclick = function() {
alert(i);
};
i++; // Come here ,i The value of is already 4 了 . therefore , When we click the button ,i The value of has always been 4
Copy code
Code 2、 In the above code , If we change to let Defining variables i:
<!DOCTYPE html>
<html lang="">
<head>
<meta />
<meta />
<meta />
<title>Document</title>
</head>
<body>
<input type="button" value="aa" />
<input type="button" value="bb" />
<input type="button" value="cc" />
<input type="button" value="dd" />
<script> var myBtn = document.getElementsByTagName("input"); for (let i = 0; i < myBtn.length; i++) { myBtn[i].onclick = function() { alert(i); }; } </script>
</body>
</html>
Copy code
The operation effect in the above code is as follows :
The above running results , That's what we expect . We use it let Defining variables i, During the cycle , Each time the loop is executed , A new... Will be born i. Loop body execution 4 Time , There will be four i.
Deconstruction and assignment of variables
ES6 Allow us , By means of arrays or objects , Assign values to a set of variables , This is called deconstruction .
Deconstruction assignment can greatly reduce the amount of our code in practical development , And make the program structure clearer .
copyright notice
author[Upwind boy],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827061052216q.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
- Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
- Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
guess what you like
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
-
Introduction to flex flexible layout in CSS -- learning notes
-
CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
-
Today, let's talk about the arrow function of ES6
-
Some thoughts on small program development
-
Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
-
Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
Random recommended
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich