The company new female intern asked me what is closure?

Code sister tease first, girls like a fairy tale.

I would first tell you a fairy tale -

// there was a princess 
// She lives in a wonderful world full of adventure 
// she met her Prince Charming, with her riding a unicorn around the world 
// and dragon fight, encountered a talking squirrel , as well as many other fantastic things. 
Princess function () { 
 var adventrures = []; 
 function princeCharming () {}; 
 var Unicorn = {}; 
 var Dragons = []; 
 var Squirrel = "the Hello!"; 
 // But she had to return to her home is full and monotonous world of adults. 
 {return 
 // She often speaks to people around her as a princess wonderful experience. 
 Story: function () { 
 return Adventures [adventures.length - 1]; 
 } 
 } 
} 
// but all they saw was a little girl telling stories about magic and fantasy 
var = littleGril Princess (); 
littleGril.story () ; 
// even the adults knew she was a real princess, they would not believe the so-called unicorns or dragons, because they never see them 
// people say they only exist in the imagination of the little girl 
// but we know the real truth
// Inside the little girl really is a princess 
copy the code

An answer stackoverflow of this story comes from, do not understand it does not matter, and so after reading this article, go back and look at this story, you will find that you have completely understood my charm, Keke @ ¥% # ............ JavaScript closures charm.

The company new female intern asked me what is closure?


What is closure?

When the function can remember where and when access lexical scope, it creates a closure, even if the function is executed outside of the current lexical scope. --- you do not know JavaScript (on a roll)

To a

function demo() {
 var a = 1;
 return function () {
 return a; 
 }
}
var a = demo();
console.log(a()); // 1
复制代码

Closure configuration

Closure consists of two parts: a function, the function and creating the environment.

In the composition of any local variable scope of the environment created by the closure.

Nature closures

Closure JavaScript function scope is in fact the side effects of the product.

Closure is a special object.

The so-called interested in flowers and flowers do not open, unintentional positive outcomes, not mean to use JavaScript closures, but because of internal JavaScript function can use variables outside the function, and the code just right in line with the definition of closure.

The company new female intern asked me what is closure?


In JavaScript, the external function call after its variable objects should be destroyed, but the closures to prevent their destruction, we can still access the variable outside the function of the object.

Further said that under normal circumstances, the scope and function of all the variables will be destroyed at the end of the function execution. However, if you create a closure, then the scope of a function will be held until the closure does not exist so far.

function addCalculator (x) {
 return function (y) {
 return x + y;
 }
}
var add1 = addCalculator(1);
console.log(add1(1)); //2
// 释放对闭包的引用
add1 = null;
console.log(add1(1)); //Uncaught TypeError: add1 is not a function
复制代码

闭包的应用

我们可以用闭包来做什么呢?

了解Java的同学可能知道,Java是支持私有方法的,私有方法只能被一个类中的其他方法所调用,但是JavaScript没有提供这种原生支持,所以我们可以通过闭包来模拟私有方法。

私有方法自然有私有方法的好处,私有方法有利于限制对代码的访问,而且可以避免非核心的方法干扰代码的公共接口,减少全局污染。

来个

var calculator = (function(){
 var a = 1;
 function addCalculator(val){
 a += val
 }
 return {
 add1:function() {
 addCalculator(1);
 },
 add2:function() {
 addCalculator(2);
 },
 result:function() {
 return a
 }
 }
})();
console.log(calculator.result()); // 1
calculator.add1();
console.log(calculator.result()); // 2
calculator.add2();
console.log(calculator.result()); // 4
复制代码

上面这种方式也叫做模块模式(module pattern)

使用闭包的注意事项

内存泄漏

因为闭包可以使函数中的变量都保存在内存中,造成很大的内存消耗,所以如果 不是某些特定的任务需要使用闭包,我们不要滥用它。

很多博客中都提到了这一点,但是其实都是不完全对的。

敲黑板!!!

使用不当的闭包会在IE(IE9)之前造成内存泄漏问题。因为它的JavaScript引擎使用的垃圾回收算法是引用计数法,对于循环引用将会导致GC(下文会介绍)无法回收垃圾。

关于各个浏览器的闭包测试,详情请见司徒正美-js闭包测试

垃圾回收机制

都9102年了,全国开始实行垃圾分类了,你居然还不知道垃圾回收机制,赶快来补习一下!

The company new female intern asked me what is closure?


垃圾回收也就是GC(Garbage Collection)。

GC把程序不用的内存空间视为垃圾,找到它们并且将它们回收,让程序员可以再次利用这部分空间。

不是所有的语言都有GC,一般存在于高级语言中,如Java、JavaScript、Python。那么在没有GC的世界里,程序员就比较辛苦,只能手动去管理内存,比如在C语言中我们可以通过malloc/free,在C++中的new/delete来进行管理。

垃圾回收算法

因为这一部分的内容很多,本文只进行简单的讲解,如果想深入了解垃圾回收算法的同学可以在文末获取学习资料。

GC标记-清除算法

世界上首个值得纪念的GC算法是GC标记-清除算法。因为自其问世以来,一直到半个世纪后的今天,它依然是各种处理程序所用的伟大的算法。

GC标记-清除算法由标记阶段和清除阶段构成,标记阶段将所有的活动对象做上相应的标记,清除阶段把那些没有标记的对象,也就是非活动对象进行回收。在搜索对象并进行标记的时候使用了深度优先搜索,尽可能的从深度上搜索树形结构。

优点:

1.算法简单,实现容易。

2.与保守式的GC算法兼容。

缺点:

1.在使用过程中会出现碎片化的情况,如同Windows的文件系统一样,导致 无数的小分块散布在堆的各个地方。

2.分配速度,由于分块的不连续性,算法每次分配的时候都需要遍历空闲链表为了找到足够大的分块,这样最糟糕的情况就是遍历到最后才找到合适的分 块,影响了分配速度。

引用计数法

这种方法中引入了计数器的概念,通过计数器来表示对象的“人气指数”,也就是有多少个程序引用了这个对象。当计数器(引用数)为0时,垃圾立刻被回收。

优点:

1.可以立即回收垃圾。

2. Maximum short pause time.

3. and there is no need to look along the pointer.

Disadvantages:

1. The above-mentioned circular reference can not be recovered.

2. and complex to implement.

3. The counter values ​​increase or decrease processing very heavy.

4. At the same time the counter needs accounted for a lot of bits, resulting in greatly reducing the efficiency of the use of memory space.

Software engineering is no silver bullet , these shortcomings have the appropriate way to resolve, if you want to learn more garbage collection algorithm, can be purchased garbage collection algorithm and implementation to see this book, it is recommended to support genuine.

The company new female intern asked me what is closure?


There are more video sharing information, plus a small Coke Ah

The company new female intern asked me what is closure?


Guess you like

Origin blog.51cto.com/14516511/2436132