javascript 闭包理解例子
function Jquery(){
this.name = 'ysr';
this.sex = 'man';
return {
x: this,
age : 26
}
}
var b = new Jquery();
//b => {x:Jquery, age:26}
//b.x = Jquery;
//b.x.name = 'ysr';
//b.x.sex = 'man'
var b = Jquery();
//b.x = window;
若果里面没return 的话;
function Jquery(){
this.name = 'ysr';
this.sex = 'man';
}
var a = new Jquery();
//a={name:'ysr',sex:'man'}
什么是闭包(closure function )
Two one sentence summaries:
- a closure is the local variables for a function — kept alive after the function has returned, or
- a closure is a stack-frame which is not deallocated when the function returns (as if a 'stack-frame' were malloc'ed instead of being on the stack!).
function sayHello(name){
var text = "Hello " + name;
function say(){ //函数里面定义函数
console.log(text);
}
return say;
}
var aa = sayHello('ysr');
aa(); // Hello ysr;
function sayHello(name){
var text = "Hello " + name;
var say = function(){ //the anonymous function
console.log(text);
}
return say;
}
var aa = sayHello('yangyu');
aa();
Whenever you see the function keyword within another function, the inner function has access to variables in the outer function.
function foo(x) {
var tmp = 3;
function bar(y) {
console.log(x + y + (++tmp)); // will log 16
}
bar(10);
}
foo(2); //This will always log 16, because bar can access the x which was defined as an argument to foo, and it can also access tmp from foo.
//That is a closure. A function doesn't have to return in order to be called a closure. Simply accessing variables outside of your immediate lexical scope creates a closure.
上面这个例子,变一下, 返回出来。!!
//The above function will also log 16, becausebarcan still refer toxandtmp, even though it is no longer directly inside the scope
function foo(x) {
var tmp = 3; return function (y) {
console.log(x + y + (++tmp)); // will also log 16
}
} var bar = foo(2); // bar is now a closure.
bar(10); //16
bar(10) //17
The simplest example of a closure is this:
var a = 10;
function test() {
console.log(a); // will output 10
console.log(b); // will output 6
}
var b = 6;
test();
When a JavaScript function is invoked, a new execution context is created. Together with the function arguments and the parent object, this execution context also receives all the variables declared outside of it (in the above example, both 'a' and 'b').
It is possible to create more than one closure function, either by returning a list of them or by setting them to global variables. All of these will refer to the same x and the same tmp, they don't make their own copies.
Here the number x is a literal number. As with other literals in JavaScript, when foo is called, the number x is copied into foo as its argument x.
On the other hand, JavaScript always uses references when dealing with objects. If say, you called foo with an object, the closure it returns will reference that original object!
function foo(x) {
var tmp = 3;
return function (y) {
console.log(x + y + tmp);
x.memb = x.memb ? x.memb + 1 : 1;
console.log(x.memb);
}
}
var age = new Number(2);
var bar = foo(age); // bar is now a closure referencing age.
bar(10);
//15
//1
bar(10)
//15
//2
function makeKitchen () {
var trashBags = ['A', 'B', 'C']; // only 3 at first
return {
getTrashBag: function() {
return trashBags.pop();
}
};
}
var kitchen = makeKitchen();
kitchen.getTrashBag(); // returns trash bag C
kitchen.getTrashBag(); // returns trash bag B
kitchen.getTrashBag(); // returns trash bag A
As expected, each call to bar(10) will increment x.memb. What might not be expected, is that x is simply referring to the same object as the age variable! After a couple of calls to bar, age.memb will be 2! This referencing is the basis for memory leaks with HTML objects.
javascript 闭包理解例子的更多相关文章
- 对于 Javascript 闭包理解
一.变量的作用域 要理解闭包,首先必须理解Javascript特殊的变量作用域. 变量的作用域无非就是两种:全局变量和局部变量. Javascript语言的特殊之处,就在于函数内部可以直接读取全局变量 ...
- JavaScript闭包理解的关键 - 作用域链
阮一峰的一篇文章已经对闭包的用途.概念讲解地相对清晰了. 闭包就是能够读取其他函数内部变量的函数. 但我认为里面对于作用域链的解释还不够清晰,这里作一些补充. 闭包之所以可以读取外部函数的内部变量,即 ...
- javascript 闭包理解
摘自:http://www.cnblogs.com/jkswjw/p/3180384.html javascript 闭包基础分享 闭包向来给包括JavaScript程序员在内的程序员以神秘,高深的感 ...
- javascript闭包理解
//闭包理解一 function superFun(){ var _super_a='a'; function subfuc(){ console.log(_super_a); } return su ...
- JavaScript 闭包的例子
例子出自<<JavaScript权威指南>>, 加上个人的理解和总结, 欢迎交流! /********************************************* ...
- JavaScript闭包理解【关键字:普通函数、闭包、解决获取元素标签索引】
以前总觉得闭包很抽象,很难理解,所以百度一下"闭包"概览,百度的解释是:“闭包是指可以包含自由(未绑定到特定对象)变量的代码块:这些变量不是在这个代码块内或者任何全局上下文中定义的 ...
- javascript闭包学习例子
javascript中的闭包个很让人头疼的概念.总结一下 闭包是指有权访问一个函数作用域中的变量的函数.创建闭包最常见的方式,是在一个函数内部创建另一个函数,用return返回出去. 使用闭包可能造成 ...
- JavaScript ——闭包理解
昨天晚上听别人谈起闭包这个东西,虽然对js有一点了解但却丝毫没有印象,今天也没什么事就顺便研究了一下满足好奇宝宝.整合于网上的理解,记录一下. 一.闭包的作用域 要理解闭包,首先必须理解Javascr ...
- 关于javascript闭包理解
闭包(closure)是Javascript语言的一个难点,也是它的特色,很多高级应用都要依靠闭包实现. 一:关于变量的作用域 Javascript语言的特殊之处,就在于函数内部可以直接读取全局变量. ...
随机推荐
- Thinkphp与Ucenter整合笔记
ucenter手册:http://www.phpddt.com/manual/ucenter/html/index.htm 参考:http://www.thinkphp.cn/topic/1557.h ...
- Mongoose如何实现统计查询、关联查询
[问题]Mongoose如何实现统计查询.关联查询 发布于 4 年前 作者 a272121742 13025 次浏览 最近业务上提出一个需求,要求能做统计,我们设计的文档集,统计可能跨越的文档会 ...
- 自定义cell,根据数据源,要对cell的布局进行调整,没有实现调整的相应效果
自定义cell,用于两种显示情况,首次进来A种情况(主材页面),正确显示,然后切换B种情况(辅材情况),可以正确显示,但是当再次切换回A种情况(主材情况)的时候,主材cell不能正常显示了,遗留的B中 ...
- UITextfield的一些属性
//设置左视图 不用设置frame UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@&quo ...
- WPF之TabControl控件用法
先创建实体基类:NotificationObject(用来被实体类继承) 实现属性更改通知接口: using System; using System.Collections.Generic; usi ...
- 8.4 sikuli 集成进eclipse 报错:Unsupported major.minor version 51.0
8.3中的问题Win32Util.dll: Can't load 32-bit .dll on a AMD 64 bit platform 解决之后,执行还是会有报错:Unsupported maj ...
- Git本地项目上传 & SourceTree & GitHub 简单使用
Git(分布式版本控制系统) Git是一款免费.开源的分布式版本控制系统,用于敏捷高效地处理任何或小或大的项目. Git是一个开源的分布式版本控制系统,用以有效.高速的处理从很小到非常大的项目版本管理 ...
- A*算法实现
A* 算法非常简单.算法维护两个集合:OPEN 集和 CLOSED 集.OPEN 集包含待检测节点.初始状态,OPEN集仅包含一个元素:开始位置.CLOSED集包含已检测节点.初始状态,CLOSED集 ...
- Hibernate锁机制
业务逻辑的实现过程中,往往需要保证数据访问的排他性.因此,我们就需要通过一些机制来保证这些数据在某个操作过程中不会被外界修改,这样的机制,在这里,也就是所谓的“锁”,即给我们选定的目标数据上锁,使其无 ...
- VNC轻松连接远程Linux桌面
VNC连接Linux桌面,要想连接Linux远程桌面,按照下面的步骤,非常简单.快速,Linux配置VNC(以RedHat.CentOS.Fedora系列为例). 工具/原料 Linux平台安装VNC ...