closures within closures in javascript
Written in front
JavaScript An almost myth For people who have experience using JavaScript but have never really understood the concept of closures, understanding closures can be a rebirth of sorts. Closures are not tools that require learning new syntax to use. Closures are a natural result of writing code based on lexical scope. In other words, you don’t need to write closures for the sake of closures; closures are everywhere in the code we write. When you really understand closures, you will find that, oh~, it turns out that there are many closures in the code I typed before!
A small demo
If we look carefully at the following examples, we will feel strange. They are all calling result(), so why are the results different?
let count=500 //全局作用域 function foo1() { let count = 0;//函数全局作用域 function foo2() { count++;//函数内部作用域 console.log(count); return count; } return foo2;//返回函数 } let result = foo1(); result();//结果为1 result();//结果为2
First of all, foo1() returns a foo2() function. When we call result(), it will return the function executed by foo2(). What is in foo2()? First we see As shown below, there is a count variable, but it is not defined. According to the definition of JavaScript scope chain, when the variables inside the function are not defined, the bubbling method will be used to search for the upper level. The upper level does not continue to the next level. Search one level until the top-level window. If there is none, an undefined error will be reported. Here we find count in foo1(), so count 1, the first output is 1, there is no problem.
function foo2() { count++; console.log(count); return count; }
But a problem occurred when we executed result() for the second time. Why is it 2? According to the process, first look for count inside the foo2() function. If there is no count, then look for it in the outer layer. Found count=0, then count 1 should be 1. This involves the issue of closure.
First we add a debugger, then right-click on Google Chrome and click on resources to see a Closure on the right. The browser's visualization has confirmed that this is indeed a closure. And count=1 has been stored in the Closure. This means count=1 has not been destroyed, and count=2 when result() is called next time.
Understanding scope
You must understand it to learn Clusure Scope-related knowledge of JavaScript includes:
1. Global scope
2. Function scope
4. Block-level scope (new in es6, solves the var problem, and adds let , const)
var count = 100; //全局作用域 function foo1() { var count = 0; //函数全局作用域 return count; //返回函数 } if (count == 1) { //块级作用域 console.log(count); }
The above code can simply show the scope classification. It should be noted that a function (function) is also a block-level scope. To put it simply, generally {} can be regarded as a block. Level scope.
Scope chain
Scopes are nested within scopes, forming a scope chain. External scopes cannot access internal scopes Scope, see the following example
function foo(){ var n=1 function foo2(){ var m=1 console.log(n) //1 } foo2() } foo() console.log(n) //err: n is not defined
In the above code, the internal n cannot be accessed globally, but the nested internal foo2() can access the external function. This is the special effect produced by the scope.
Now that we understand the scope chain, let’s look at an example (it’s very confusing, look carefully):
var name = 'Mike'; //第一次定义name function showName() { console.log(name); //输出 Mike 还是 Jay ? } function changeName() { var name = 'Jay'; //重新定义name showName(); //调用showName() } changeName();
What do you think the output of the above example is? The answer is Mike. Here we introduce a new concept. There are two models of lexical scope:
Lexical scope (static): js search is determined according to the position when the code is written , rather than according to the position when calling
Dynamic scope: Perl and Bash are currently used (you can learn about it yourself)
We can analyze it again through the rules of lexical scope
When calling changeName(), find this function
Define var name = "Jay"
Call showName()
Check if there is showName() in changeName() This method was not found, so I searched the outer layer and found
. Call console.log(name) and searched inside the function to see if there is a name. If not, I searched outward and found it. name="Mike"
Output Mike
Closure
Understood After the above knowledge, I finally came to closure
The official explanation of closure in two books:
##1. Little "yellow" book (you don't know JavaScript): Closure is generated when a function can remember and access the lexical scope it is in, even if the function is executed outside the current lexical scope.is a very abstract concept. One of my own understandings is:2. Little Red Book (JavaScript Advanced Programming) : Closure means having access to another The function of variables in function scope
When a variable (like the name above) is neither local to the function A variable is not a parameter of the function. Compared with the scope, it is a free variable (referring to an external variable), which will form a closure.
How to say it? Let’s take a look at what we use at the beginning demo
let count = 500; //全局作用域 function foo1() { let count = 0; //函数全局作用域 function foo2() { let count2 = 1; //随便新增一个变量 // count++; 注释 debugger; //console.log(count); 注释 //return count; 注释 } return foo2; //返回函数 } let result = foo1(); result(); //结果为1 result(); //结果为2
再次使用浏览器看看,这时我们就发现Closure已经消失了,这也就证实我说的,如果函数内部不调用外部的变量,就不会形成闭包.但是如果调用了外部变量,那么就会形成闭包. 这也就是说不是所有的函数嵌套函数都能形成闭包
<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/731/425/784/1592270826700856.jpg" class="lazy" title="1592270826700856.jpg" alt="closures within closures in javascript"/>
最后我们再来看一个循环闭包的例子
for (var i = 1; i <= 5; i++) { setTimeout(function timer() { debugger; console.log(i); // 输出什么? }, 1000); }
答案 6 6 6 6 6 .因为setTimeout里面的回调函数是一个异步的过程(异步代表可以不用等待我这个代码先执行完,可以先往后执行),而for循环是同步的(代码只能从上往下的执行),立即执行,异步的setTimeout必须等待一秒才能执行,这时i早已经循环结束了.
解决办法有三个:
将for循环中的var 改成let
for (let i = 1; i <= 5; i++) { setTimeout(function timer() { debugger; console.log(i); // 1 2 3 4 5 }, 1000); }
这样就没有问题了, 因为let是有块级的功能,每一层循环都是独立的,互不影响,所以才能正常输出.
2. 把setTimeout()套上一个function
for (var i = 1; i <= 5; i++) { log(i); // 1 2 3 4 5 } function log(i) { setTimeout(function timer() { debugger; console.log(i); }, 1000); }
这样同样能够实现这个功能,原理和第一个方法一样,每一个log()都是独立的,互不影响,这样才能有正确的结果,var就是因为没有块级的功能,才会出问题 3. 包装成匿名函数
for (var i = 1; i <= 5; i++) { (function (i) { setTimeout(function timer() { debugger; console.log(i); }, 1000); })(i) }
前面一个(func..)
定义函数,后面一个(i)调用,这再JavaScript叫做立即执行函数,其实与第二种方式是一样的,只是写法不一样.
结语
理解JavaScript闭包是一项重要的技能,在面试中也常常会有,这是迈进高级JavaScript工程师的必经之路.
推荐教程: 《js教程》
The above is the detailed content of closures within closures in javascript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
