Javascript之闭包理解
来源:互联网 发布:java jdbc 连接 编辑:程序博客网 时间:2024/06/04 20:13
闭包概念 An inner function always has access to the vars and parameters of its outer function, even after the outer function has returned…
内部函数始终可以访问外部函数的变量及参数,即使外部函数被返回。
由于外部函数不能访问内部函数(js作用域链,大家懂的),但是有时候需要在外部访问内部函数中的变量。相反,因为内部函数可以访问外部变量,因此一般是在函数中嵌套一个内部函数,并返回这个内部函数,在这个内部函数中是可以访问父变量对象中的变量的。所以通过返回内部函数,那么在全局作用域中就可以访问函数内部的变量了。为了简单理解,还是赶紧给出example咯:
function foo() { var a = 'private variable'; return function bar() { alert(a); }}var callAlert = foo();callAlert(); // private variable
// Global Context when evaluatedglobal.VO = { foo: pointer to foo(), callAlert: returned value of global.VO.foo scopeChain: [global.VO]}// Foo Context when evaluatedfoo.VO = { bar: pointer to bar(), a: 'private variable', scopeChain: [foo.VO, global.VO]}// Bar Context when evaluatedbar.VO = { scopeChain: [bar.VO, foo.VO, global.VO]}
By alerting a
, the interpreter checks the first VO in thebar.VO.scopeChain
for a property named a
but can not find a match, so promptly moves on to the next VO, foo.VO
.
It checks for the existence of the property and this time finds a match, returning the value back to the bar
context, which explains why thealert
gives us 'private variable'
even though foo()
had finished executing sometime ago.
By this point in the article, we have covered the details of thescope chain
and its lexical
environment, along with how closures
andvariable resolution
work.
- Javascript之闭包理解
- 深入理解javascript之闭包
- 深入理解javascript之闭包
- JavaScript 之理解closure(闭包)
- JavaScript之深入理解闭包
- javascript最难理解之闭包
- JavaScript深入理解之闭包
- javascript之初步理解闭包
- javascript之闭包的理解
- 理解 JavaScript 闭包
- 理解 JavaScript 闭包
- 理解 JavaScript 闭包
- 理解 JavaScript 闭包
- 理解 JavaScript 闭包
- 理解 JavaScript 闭包
- 理解 JavaScript 闭包
- 理解 JavaScript 闭包
- javascript 闭包理解
- BEM命名
- mysql-5.6.24设置数据库编码
- 7.6 鼠标的滚轮
- MFC下的键盘响应代码
- ibeacon微信摇一摇周边应用平台cloud.i-io2o.com
- Javascript之闭包理解
- Android Volley(四)自定义各种request
- Ubuntu上搭建Hadoop环境
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- QT读写Mac 系统的注册文件(.plist文件)
- Android客户端与服务器交互,登录案例
- charles抓包
- WebView
- android GoogleMap画导航线路图 路径规划(Directions)