Home >Web Front-end >JS Tutorial >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="https://img.php.cn/upload/image/731/425/784/1592270826700856.jpg" 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!