How do JavaScript closures work?
|
Like the old Albert Einstein said:
Well, I tried to explain JavaScript closures to a 27-year-old friend and completely failed. How would you explain it to someone with a knowledge of the concepts which make up closures (for example, functions, variables and the like), but does not understand closures themselves? I have seen the Scheme example given on Stack Overflow, and it did not help.
|
|||||||||||||||||||||
|
JavaScript Closures for Dummies
Closures Are Not MagicThis page explains closures so that a programmer can understand them — using working JavaScript code. It is not for gurus or functional programmers. Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any academic papers or academically oriented information about them! This article is intended for programmers with some programming experience in a mainstream language, and who can read the following JavaScript function:
An Example of a ClosureTwo one sentence summaries:
The following code returns a reference to a function:
Most JavaScript programmers will understand how a reference to a function is returned to a variable ( There is a critical difference between a C pointer to a function and a JavaScript reference to a function. In JavaScript, you can think of a function reference variable as having both a pointer to a function as well as a hidden pointer to a closure. The above code has a closure because the anonymous function In C, and most other common languages after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables can remain accessible after returning from the function you called. This is demonstrated above, because we call the function
Looking at the output of The magic is that in JavaScript a function reference also has a secret reference to the closure it was created in — similar to how delegates are a method pointer plus a secret reference to an object. More examplesFor some reason, closures seem really hard to understand when you read about them, but when you see some examples you can click to how they work (it took me a while). I recommend working through the examples carefully until you understand how they work. If you start using closures without fully understanding how they work, you would soon create some very weird bugs! Example 3This example shows that the local variables are not copied — they are kept by reference. It is kind of like keeping a stack-frame in memory when the outer function exits!
Example 4All three global functions have a common reference to the same closure because they are all declared within a single call to
The three functions have shared access to the same closure — the local variables of Note that in the above example, if you call Example 5This one is a real gotcha for many people, so you need to understand it. Be very careful if you are defining a function within a loop: the local variables from the closure do not act as you might first think.
The line
Note that when you run the example, Example 6This example shows that the closure contains any local variables that were declared inside the outer function before it exited. Note that the variable
Tricky: note also that the Example 7This final example shows that each call creates a separate closure for the local variables. There is nota single closure per function declaration. There is a closure for each call to a function.
SummaryIf everything seems completely unclear then the best thing to do is to play with the examples. Reading an explanation is much harder than understanding examples. My explanations of closures and stack-frames, etc. are not technically correct — they are gross simplifications intended to help understanding. Once the basic idea is grokked, you can pick up the details later. Final points:
Links
ThanksIf you have just learnt closures (here or elsewhere!), then I am interested in any feedback from you about any changes you might suggest that could make this article clearer. Send an email to morrisjohns.com (morris_closure @). Please note that I am not a guru on JavaScript — nor on closures. |
How do JavaScript closures work?的更多相关文章
- JavaScript——closures(待续)
问答原文:How do JavaScript closures work?
- JavaScript Closures 闭包
在一些编程语言中, 当我们执行完成function中的局部代码仅在函数执行期间可运行. 但是JS 事不一样的 闭包总结来说, 就是innerFunction 总是有使用outer function 的 ...
- 深入理解JavaScript系列(16):闭包(Closures)
介绍 本章我们将介绍在JavaScript里大家经常来讨论的话题 —— 闭包(closure).闭包其实大家都已经谈烂了.尽管如此,这里还是要试着从理论角度来讨论下闭包,看看ECMAScript中的闭 ...
- JavaScript:内存泄露、性能调优
1.在进行JS内存泄露检查之前,先要了解JS的内存管理: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Manageme ...
- JavaScript之闭包
JavaScript之闭包 在JavaScript中,闭包恐怕是很多人不能理解的一个概念了,甚至很多人也会把闭包和匿名函数混淆. 闭包是有权访问另一个函数作用域中的变量的函数.首先要明白的就是,闭包是 ...
- 理解和使用 JavaScript 中的回调函数
理解和使用 JavaScript 中的回调函数 标签: 回调函数指针js 2014-11-25 01:20 11506人阅读 评论(4) 收藏 举报 分类: JavaScript(4) 目录( ...
- [译]JavaScript规范-葵花宝典
[译]JavaScript规范 译自:https://github.com/airbnb/javascript 类型 原始值: 相当于传值 string number boolean null und ...
- JavaScript闭包的底层运行机制
转自:http://blog.leapoahead.com/2015/09/15/js-closure/ 我研究JavaScript闭包(closure)已经有一段时间了.我之前只是学会了如何使用它们 ...
- 什么是JavaScript闭包终极全解之一——基础概念
本文转自:http://www.cnblogs.com/richaaaard/p/4755021.html 什么是JavaScript闭包终极全解之一——基础概念 “闭包是JavaScript的一大谜 ...
随机推荐
- 学习笔记——中介者模式Mediator
中介者模式,A与B之间存在调用对方操作的行为,通过中介者模式,可以去除双方的强引用.如图,A可以通过代理Mediator的方法来调用B的方法,而不需要保存B的引用.
- Android PagerAdapter的用法
转http://blog.csdn.net/look85/article/details/8563906 在写这个之前,真心需要吐槽一下…关于Android开发中,PageAdapter的用法在网上能 ...
- POJ 3548 Restoring the digits
暴力搜索.注意题目说每个字母对应的数字不同,这句话表明最多只有10个字母,所以暴力DFS绝对不会TLE. #include<cstdio> #include<cstring> ...
- scala map
map 返回元组 下面是如果不存在key 报错 a.(2) 下面两种方式 不同的写法. 如果存在 Some(2) 不存在 None a get 2 a.get(2) getOrElse 如果不存在 回 ...
- 《C++ Primer》之重载操作符与转换(中)
赋值操作符 类赋值操作符接受类类型形参,通常,该形参是对类类型的 const 引用,但也可以是类类型或对类类型的非 const 引用.如果没有定义这个操作符,则编译器将合成它.类赋值操作符必须是类的成 ...
- JavaScript 错误 - Throw、Try 和 Catch
http://www.w3school.com.cn/js/js_errors.asp try 语句测试代码块的错误.catch 语句处理错误.throw 语句创建自定义错误. 错误一定会发生 当 J ...
- crossdomain 可用
<cross-domain-policy> <allow-access-from domain="*"/> <allow-http-request-h ...
- postgres 数据库备份恢复
postgre 数据库备份恢复命令 备份:pg_dump -U postgres -v -F c -Z 4 -f ***.backup dbname 9压缩率最狠恢复:pg_restore -U p ...
- vb6 控件未注册问题解决
打开项目时弹出如题错误. 另附一个帖子:http://bbs.csdn.net/topics/390580540,这个帖子讨论的不错,可以提供很多思路. 解决办法:http://rewwensoftw ...
- sqlserver 批量修改表前缀
先把第一句话放到sqlserver查询器中执行一下.然后把查询结果复制出来,进行编辑...一看你就懂了..简单的sql语句拼装 select ' exec sp_rename "' + na ...