closure: func with reference to its lexical env

closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

闭包的原理? lexical scoping

闭包是基于词法作用域写代码所产生的自然结果

Closures are functions that have access to the variables that are present in their scope chain even if the outer function ceases to exist.

当函数可以记住并访问所在的词法作用域时,就产生了闭包,即使函数是在当前词法作用域之外执行

By definition, closure is a combination of a function that remembers its global variable. When the function is called Javascript creates execution context which is a specification that contains information of all variables and properties. It is called lexical environment.

Normally, a lexical environment goes to void when the execution context is removed from the execution context stack. However, there is an exception to it. It is still accessible as long as it is reachable from another execution context.

This unique behaviour enables the nested function to access its outer variable after the function is called.

This tackles the problem coming from placing variables on the very global level of codes. When variables are declared at the global level, there is a possibility that one has the same name as another which will cause the application to crash, or malfunction. Closure ensures that the declared variables are secure from such issues.

example:

var add = (function () {

    var counter = 0;

      return function () {

        counter += 1; 

        return counter;

    }

})();

add();

add();

add();// the counter is now 3

闭包的一部分: 词法作用域查找规则
函数在定义时的词法作用域之外执行
将内部函数传递到所在的词法作用域以外,它会持有对原始定义作用域的引用
回调函数使用闭包

Practical Usage:

Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.

Consequently, you can use a closure anywhere that you might normally use an object with only a single method.

Situations where you might want to do this are particularly common on the web. Much of the code we write in front-end JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.

延迟函数的回调会在循环结束时才执行
每个迭代IIFE生成新的作用域

闭包里怎么用setTimeout?

1.使用IIFE传参创建闭包

由于setTimeout异步执行的特性,所以定义一个IIFE先把i的值传入进来,避免在执行setTimeout的时候i的值变为4

for (var i=0; i<5; i++) {

    (function (j) {

        setTimeout(() => console.log(i),1000*j)

    })(i) 

 }

let块作用域

2.块作用域let

隔一秒输出一个数:

for (let i=0; i<5; i++) {

        setTimeout(() => console.log(i),1000*i)

}

用setTimeout写一个倒计时输出5,4,3,2,1

for (let i=5; i>0; i--) {

        setTimeout(() => console.log(i),1000*(5-i))

}

模块
模块返回内部函数的引用
模块
在模块内部保留对公共API的引用

闭包:实现外部作用域访问内部作用域的变量的方法。得益于函数可以作为参数或者返回值将内部函数传递到所在的词法作用域以外,它会持有对原始定义作用域的引用。

闭包为什么会导致作用域链不释放?如果有变量引用闭包所返回的函数,那个这个函数将不会释放,同时也使原始作用域不会得到释放。除非不再有引用,才会释放。


如果去掉了所有闭包功能,会出现什么问题?


应用场景:创建私有变量,柯里,防抖节流

缺点:内存泄漏


There are two main disadvantages of overusing closures:

-The variables declared inside a closure are not garbage collected. 闭包是不回收引用的那个对象还是不回收整个外部作用域,怎么验证这一点?

-Too many closures can slow down your application. This is actually caused by duplication of code in the memory.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,809评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,189评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,290评论 0 359
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,399评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,425评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,116评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,710评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,629评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,155评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,261评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,399评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,068评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,758评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,252评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,381评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,747评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,402评论 2 358

推荐阅读更多精彩内容