Home >Web Front-end >JS Tutorial >Closures have something to say - big front end
When I first learned the front-end, I was always confused when I saw the word closure. During the interview, when I was asked this question, my answer was vague, and I always felt that there were layers of confusion. Diaphragm, I think this concept is very magical. If you can master it, your skill will be greatly improved. In fact, closure is not so mysterious, it is everywhere.
First, let’s look at a question.
Please describe what a closure is in one sentence and write the code to illustrate.
If you can say it without hesitation and give an explanation, then there is no need for you to read the following text.
Regarding this issue, combined with the information and experience I have reviewed, I will briefly talk about it here. If there is anything wrong, please correct me.
First answer the above question, what is closure.
Closure is a concept that describes the phenomenon that a function still resides in memory after it is executed.
Code description:
function foo() { var a = 2; function bar(){ console.log(a); } return bar; } var test = foo(); test(); //2
The above code clearly shows the closure.
The lexical scope of function bar() has access to the internal scope of foo(). Then we pass the bar() function itself as a value type. In the above example, we use the function object itself referenced by bar() as the return value.
After foo() is executed, its internal scope has not been destroyed, because bar() still maintains a reference to the internal scope. Thanks to the position of bar(), it has coverage of foo() ) closure of the internal scope, allowing the scope to survive for bar() to reference at any time. This reference is actually a closure.
It is for this reason that when test is actually called, it can access the lexical scope when it is defined, so it can access a.
Function transfer can also be indirect:
var fn; function foo(){ var a = 2; function baz() { console.log( a ); } fn = baz; //将baz 分配给全局变量 } function bar(){ fn(); } foo(); bar(); //2
So, no matter how the inner function is passed outside its lexical scope, it will hold a reference to the original definition scope. That is, wherever this function is executed, the closure will be used. It is also for this reason that we can use the callback function very conveniently without caring about its specific details.
In fact, in timers, event listeners, ajax requests, cross-window communication, Web Workers or any other synchronous or asynchronous tasks, as long as you use a callback function, you are actually using a closure. Bag.
At this point, maybe you already have a general understanding of closures. Let me give you a few more examples to help you deepen your understanding of closures.
First of all, let’s take a look at the so-called immediate execution function.
var a = 2; (function IIFE() { console.log(a); })(); //2
This immediate execution function is usually considered a classic closure example , which works fine, but is not strictly a closure.
why?
Because this IIFE function is not executed outside its own lexical scope. It is executed in the scope in which it was defined. Furthermore, variable a is looked up through ordinary lexical scope, not through closures.
Another example used to illustrate closures is a loop.
<p class="tabs"> <li class="tab">some text1</li> <li class="tab">some text2</li> <li class="tab">some text3</li> </p>
var handler = function(nodes) { for(var i = 0, l = nodes.length; i < l ; i++) { nodes[i].onclick = function(){ console.log(i); } } } var tabs = document.querySelectorAll('.tabs .tab'); handler(tabs);
Our expected result is log 0, 1, 2;
The result after execution is three 3;
Why is this?
First explain how this 3 comes from.
Look at the loop body. The termination condition of the loop is i < l. The value of i is 3 when the condition is established for the first time.
Therefore, the output shows the final value of i at the end of the loop. According to the working principle of scope, although the functions in the loop are defined separately in each iteration, they are all enclosed in a shared global scope, so there is actually only one i.
handler The original intention of the function was to pass the unique i to the event handler, but it failed.
Because the event handler function binds i itself, not the value of i when the function is constructed.
After knowing this, we can make corresponding adjustments:
var handler = function(nodes) { var helper = function(i){ return function(e){ console.log(i); // 0 1 2 } } for(var i = 0, l = nodes.length; i < l ; i++) { nodes[i].onclick = helper(i); } }
Create an auxiliary function outside the loop, and let this auxiliary function return a function bound to the current value of i, so that there will be no confusion.
Understanding this, you will find that the above processing is to create a new scope. In other words, we need a block scope for each iteration.
Speaking of For block scope, we have to mention one word, that is let.
So, if you don’t want to use closures too much, you can use let:
var handler = function(nodes) { for(let i = 0, l = nodes.length; i < l ; i++) { //nodes[i].index = i; nodes[i].onclick = function(){ console.log(i); // 0 1 2 } } }
Let’s look at an example first
var sel = $("#con"); setTimeout( function (){ sel.css({background:"gray"}); }, 2000);
The above code uses jQuery’s selector to find the element with the id con, register a timer, and after two seconds, set the background color to gray.
The magic of this code snippet is that after calling the setTimeout function, con is still kept inside the function. After two seconds, the background color of the p element with the id con is indeed changed. It should be noted that setTimeout has returned after the call, but con has not been released. This is because con refers to the variable con in the global scope.
The above examples help us understand more details about closures. Let’s explore the world of closures in depth.
首先看一个概念-执行上下文(Execution Context)。
执行上下文是一个抽象的概念,ECMAScript 规范使用它来追踪代码的执行。它可能是你的代码第一次执行或执行的流程进入函数主体时所在的全局上下文。
在任意一个时间点,只能有唯一一个执行上下文在运行之中。
这就是为什么 JavaScript 是“单线程”的原因,意思就是一次只能处理一个请求。
一般来说,浏览器会用栈来保存这个执行上下文。
栈是一种“后进先出” (Last In First Out) 的数据结构,即最后插入该栈的元素会最先从栈中被弹出(这是因为我们只能从栈的顶部插入或删除元素)。
当前的执行上下文,或者说正在运行中的执行上下文永远在栈顶。
当运行中的上下文被完全执行以后,它会由栈顶弹出,使得下一个栈顶的项接替它成为正在运行的执行上下文。
除此之外,一个执行上下文正在运行并不代表另一个执行上下文需要等待它完成运行之后才可以开始运行。
有时会出现这样的情况,一个正在运行中的上下文暂停或中止,另外一个上下文开始执行。暂停的上下文可能在稍后某一时间点从它中止的位置继续执行。
一个新的执行上下文被创建并推入栈顶,成为当前的执行上下文,这就是执行上下文替代的机制。
当我们有很多执行上下文一个接一个地运行时——通常情况下会在中间暂停然后再恢复运行——为了能很好地管理这些上下文的顺序和执行情况,我们需要用一些方法来对其状态进行追踪。而实际上也是如此,根据ECMAScript的规范,每个执行上下文都有用于跟踪代码执行进程的各种状态的组件。包括:
代码执行状态:任何需要开始运行,暂停和恢复执行上下文相关代码执行的状态
函数:上下文中正在执行的函数对象(正在执行的上下文是脚本或模块的情况下可能是null)
Realm:一系列内部对象,一个ECMAScript全局环境,所有在全局环境的作用域内加载的ECMAScript代码,和其他相关的状态及资源。
词法环境:用于解决此执行上下文内代码所做的标识符引用。
变量环境:一种词法环境,该词法环境的环境记录保留了变量声明时在执行上下文中创建的绑定关系。
现在的开发都离不开模块化,下面说说模块是如何利用闭包的。
先看一个实际中的例子。
这是一个统计模块,看一下代码:
define("components/webTrends", ["webTrendCore"], function(require,exports, module) { var webTrendCore = require("webTrendCore"); var webTrends = { init:function (obj) { var self = this; self.dcsGetId(); self.dcsCollect(); }, dcsGetId:function(){ if (typeof(_tag) != "undefined") { _tag.dcsid="dcs5w0txb10000wocrvqy1nqm_6n1p"; _tag.dcsGetId(); } }, dcsCollect:function(){ if (typeof(_tag) != "undefined") { _tag.DCSext.platform="weimendian"; if(document.readyState!="complete"){ document.onreadystatechange = function(){ if(document.readyState=="complete") _tag.dcsCollect() } } else _tag.dcsCollect() } } }; module.exports = webTrends; })
在主页面使用的时候,调用一下就可以了:
var webTrends = require("webTrends"); webTrends.init();
在定义的模块中,我们暴露了webTrends对象,在外面调用返回对象中的方法就形成了闭包。
模块的两个必要条件:
必须有外部的封闭函数,该函数必须至少被调用一次
封闭函数必须返回至少一个内部函数,这样内部函数才能在私有作用域中形成闭包,并且可以访问或者修改私有的状态。
如果一个任务不需要使用闭包,那最好不要在函数内创建函数。
原因很明显,这会 拖慢脚本的处理速度,加大内存消耗 。
举个例子,当需要创建一个对象时,方法通常应该和对象的原型关联,而不是定义到对象的构造函数中。 原因是 每次构造函数被调用, 方法都会被重新赋值 (即 对于每个对象创建),这显然是一种不好的做法。
看一个能说明问题,但是不推荐的做法:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); this.getName = function() { return this.name; }; this.getMessage = function() { return this.message; }; }
上面的代码并没有很好的利用闭包,我们来改进一下:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } MyObject.prototype = { getName: function() { return this.name; }, getMessage: function() { return this.message; } };
好一些了,但是不推荐重新定义原型,再来改进下:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } MyObject.prototype.getName = function() { return this.name; }; MyObject.prototype.getMessage = function() { return this.message; };
很显然,在现有的原型上添加方法是一种更好的做法。
上面的代码还可以写的更简练:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } (function() { this.getName = function() { return this.name; }; this.getMessage = function() { return this.message; }; }).call(MyObject.prototype);
在前面的三个示例中,继承的原型可以由所有对象共享,并且在每个对象创建时不需要定义方法定义。如果想看更多细节,可以参考对象模型。
使用闭包可以在JavaScript中模拟块级作用域;
Closures can be used to create private variables in objects.
Advantages:
Logical continuity, when the closure is used as a parameter of another function call This prevents you from deviating from the current logic and writing additional logic separately.
Conveniently calls local variables of the context.
Strengthen encapsulation, and the extension of point 2 can achieve the protection of variables.
Disadvantages:
Waste of memory. This memory waste is not only because it is resident in memory, but improper use of closures will cause the generation of invalid memory.
I have made some simple explanations about closures before. Finally, let me summarize. In fact, there is nothing special about closures. Its characteristics are:
Function nested function
You can access external variables or objects inside the function
Avoid garbage Recycling
Welcome to communicate, above;-)
Let’s learn JavaScript closures together
Understand JavaScript Scope and Closures
Closures
When I first learned the front-end, I saw this closure I always feel confused about Ci. When I was asked this question during the interview, my answer was vague. I always felt that there was a barrier. I thought this concept was very magical. If I could master it, my skills would be greatly improved. In fact, closure is not so mysterious, it is everywhere.
First, let’s look at a question.
Please describe what a closure is in one sentence and write the code to illustrate.
If you can say it without hesitation and give an explanation, then there is no need for you to read the following text.
Regarding this issue, combined with the information and experience I have reviewed, I will briefly talk about it here. If there is anything wrong, please correct me.
First answer the above question, what is closure.
Closure is a concept that describes the phenomenon that a function still resides in memory after it is executed.
Code description:
function foo() { var a = 2; function bar(){ console.log(a); } return bar; } var test = foo(); test(); //2
The above code clearly shows the closure.
The lexical scope of function bar() has access to the internal scope of foo(). Then we pass the bar() function itself as a value type. In the above example, we use the function object itself referenced by bar() as the return value.
After foo() is executed, its internal scope has not been destroyed, because bar() still maintains a reference to the internal scope. Thanks to the position of bar(), it has coverage of foo() ) closure of the internal scope, allowing the scope to survive for bar() to reference at any time. This reference is actually a closure.
It is for this reason that when test is actually called, it can access the lexical scope when it is defined, so it can access a.
Function transfer can also be indirect:
var fn; function foo(){ var a = 2; function baz() { console.log( a ); } fn = baz; //将baz 分配给全局变量 } function bar(){ fn(); } foo(); bar(); //2
So, no matter how the inner function is passed outside its lexical scope, it will hold a reference to the original definition scope. That is, wherever this function is executed, the closure will be used. It is also for this reason that we can use the callback function very conveniently without caring about its specific details.
In fact, in timers, event listeners, ajax requests, cross-window communication, Web Workers or any other synchronous or asynchronous tasks, as long as you use a callback function, you are actually using a closure. Bag.
At this point, maybe you already have a general understanding of closures. Let me give you a few more examples to help you deepen your understanding of closures.
First of all, let’s take a look at the so-called immediate execution function.
var a = 2; (function IIFE() { console.log(a); })(); //2
This immediate execution function is usually considered a classic closure example , which works fine, but is not strictly a closure.
why?
Because this IIFE function is not executed outside its own lexical scope. It is executed in the scope in which it was defined. Furthermore, variable a is looked up through ordinary lexical scope, not through closures.
Another example used to illustrate closures is a loop.
<p class="tabs"> <li class="tab">some text1</li> <li class="tab">some text2</li> <li class="tab">some text3</li> </p>
var handler = function(nodes) { for(var i = 0, l = nodes.length; i < l ; i++) { nodes[i].onclick = function(){ console.log(i); } } } var tabs = document.querySelectorAll('.tabs .tab'); handler(tabs);
Our expected result is log 0, 1, 2;
The result after execution is three 3;
Why is this?
First explain how this 3 comes from.
Look at the loop body. The termination condition of the loop is i < l. The value of i is 3 when the condition is established for the first time.
Therefore, the output shows the final value of i at the end of the loop. According to the working principle of scope, although the functions in the loop are defined separately in each iteration, they are all enclosed in a shared global scope, so there is actually only one i.
handler The original intention of the function was to pass the unique i to the event handler, but it failed.
Because the event handler function binds i itself, not the value of i when the function is constructed.
After knowing this, we can make corresponding adjustments:
var handler = function(nodes) { var helper = function(i){ return function(e){ console.log(i); // 0 1 2 } } for(var i = 0, l = nodes.length; i < l ; i++) { nodes[i].onclick = helper(i); } }
在循环外创建一个辅助函数,让这个辅助函数在返回一个绑定了当前i的值的函数,这样就不会混淆了。
明白了这点,就会发现,上面的处理就是为了创建一个新的作用域,换句话说,每次迭代我们都需要一个块作用域.
说到块作用域,就不得不提一个词,那就是let.
所以,如果你不想过多的使用闭包,就可以使用let:
var handler = function(nodes) { for(let i = 0, l = nodes.length; i < l ; i++) { //nodes[i].index = i; nodes[i].onclick = function(){ console.log(i); // 0 1 2 } } }
先来看个例子
var sel = $("#con"); setTimeout( function (){ sel.css({background:"gray"}); }, 2000);
上边的代码使用了 jQuery 的选择器,找到 id 为 con 的元素,注册计时器,两秒之后,将背景色设置为灰色。
这个代码片段的神奇之处在于,在调用了 setTimeout 函数之后,con 依旧被保持在函数内部,当两秒钟之后,id 为 con 的 p 元素的背景色确实得到了改变。应该注意的是,setTimeout 在调用之后已经返回了,但是 con 没有被释放,这是因为 con 引用了全局作用域里的变量 con。
以上的例子帮助我们了解了更多关于闭包的细节,下面我们就深入闭包世界探寻一番。
首先看一个概念-执行上下文(Execution Context)。
执行上下文是一个抽象的概念,ECMAScript 规范使用它来追踪代码的执行。它可能是你的代码第一次执行或执行的流程进入函数主体时所在的全局上下文。
在任意一个时间点,只能有唯一一个执行上下文在运行之中。
这就是为什么 JavaScript 是“单线程”的原因,意思就是一次只能处理一个请求。
一般来说,浏览器会用栈来保存这个执行上下文。
栈是一种“后进先出” (Last In First Out) 的数据结构,即最后插入该栈的元素会最先从栈中被弹出(这是因为我们只能从栈的顶部插入或删除元素)。
当前的执行上下文,或者说正在运行中的执行上下文永远在栈顶。
当运行中的上下文被完全执行以后,它会由栈顶弹出,使得下一个栈顶的项接替它成为正在运行的执行上下文。
除此之外,一个执行上下文正在运行并不代表另一个执行上下文需要等待它完成运行之后才可以开始运行。
有时会出现这样的情况,一个正在运行中的上下文暂停或中止,另外一个上下文开始执行。暂停的上下文可能在稍后某一时间点从它中止的位置继续执行。
一个新的执行上下文被创建并推入栈顶,成为当前的执行上下文,这就是执行上下文替代的机制。
当我们有很多执行上下文一个接一个地运行时——通常情况下会在中间暂停然后再恢复运行——为了能很好地管理这些上下文的顺序和执行情况,我们需要用一些方法来对其状态进行追踪。而实际上也是如此,根据ECMAScript的规范,每个执行上下文都有用于跟踪代码执行进程的各种状态的组件。包括:
代码执行状态:任何需要开始运行,暂停和恢复执行上下文相关代码执行的状态
函数:上下文中正在执行的函数对象(正在执行的上下文是脚本或模块的情况下可能是null)
Realm:一系列内部对象,一个ECMAScript全局环境,所有在全局环境的作用域内加载的ECMAScript代码,和其他相关的状态及资源。
词法环境:用于解决此执行上下文内代码所做的标识符引用。
变量环境:一种词法环境,该词法环境的环境记录保留了变量声明时在执行上下文中创建的绑定关系。
现在的开发都离不开模块化,下面说说模块是如何利用闭包的。
先看一个实际中的例子。
这是一个统计模块,看一下代码:
define("components/webTrends", ["webTrendCore"], function(require,exports, module) { var webTrendCore = require("webTrendCore"); var webTrends = { init:function (obj) { var self = this; self.dcsGetId(); self.dcsCollect(); }, dcsGetId:function(){ if (typeof(_tag) != "undefined") { _tag.dcsid="dcs5w0txb10000wocrvqy1nqm_6n1p"; _tag.dcsGetId(); } }, dcsCollect:function(){ if (typeof(_tag) != "undefined") { _tag.DCSext.platform="weimendian"; if(document.readyState!="complete"){ document.onreadystatechange = function(){ if(document.readyState=="complete") _tag.dcsCollect() } } else _tag.dcsCollect() } } }; module.exports = webTrends; })
在主页面使用的时候,调用一下就可以了:
var webTrends = require("webTrends"); webTrends.init();
在定义的模块中,我们暴露了webTrends对象,在外面调用返回对象中的方法就形成了闭包。
模块的两个必要条件:
必须有外部的封闭函数,该函数必须至少被调用一次
封闭函数必须返回至少一个内部函数,这样内部函数才能在私有作用域中形成闭包,并且可以访问或者修改私有的状态。
如果一个任务不需要使用闭包,那最好不要在函数内创建函数。
原因很明显,这会 拖慢脚本的处理速度,加大内存消耗 。
举个例子,当需要创建一个对象时,方法通常应该和对象的原型关联,而不是定义到对象的构造函数中。 原因是 每次构造函数被调用, 方法都会被重新赋值 (即 对于每个对象创建),这显然是一种不好的做法。
看一个能说明问题,但是不推荐的做法:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); this.getName = function() { return this.name; }; this.getMessage = function() { return this.message; }; }
上面的代码并没有很好的利用闭包,我们来改进一下:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } MyObject.prototype = { getName: function() { return this.name; }, getMessage: function() { return this.message; } };
好一些了,但是不推荐重新定义原型,再来改进下:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } MyObject.prototype.getName = function() { return this.name; }; MyObject.prototype.getMessage = function() { return this.message; };
很显然,在现有的原型上添加方法是一种更好的做法。
上面的代码还可以写的更简练:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } (function() { this.getName = function() { return this.name; }; this.getMessage = function() { return this.message; }; }).call(MyObject.prototype);
在前面的三个示例中,继承的原型可以由所有对象共享,并且在每个对象创建时不需要定义方法定义。如果想看更多细节,可以参考对象模型。
使用闭包可以在JavaScript中模拟块级作用域;
闭包可以用于在对象中创建私有变量。
优点:
逻辑连续,当闭包作为另一个函数调用的参数时,避免你脱离当前逻辑而单独编写额外逻辑。
方便调用上下文的局部变量。
加强封装性,第2点的延伸,可以达到对变量的保护作用。
缺点:
内存浪费。这个内存浪费不仅仅因为它常驻内存,对闭包的使用不当会造成无效内存的产生。
前面对闭包做了一些简单的解释,最后再总结下,其实闭包没什么特别的,其特点是:
函数嵌套函数
函数内部可以访问到外部的变量或者对象
避免了垃圾回收
更多闭包有话说 - 大前端相关文章请关注PHP中文网!