易截截图软件、单文件、免安装、纯绿色、仅160KB

Javascript闭包(Closure)

Closure中文翻译为闭包.字面上来理解就是"封闭的包".(这是一句废话)
闭包是什么?
书面解释为:
所谓“闭包”,指的是一个拥有许多变量和绑定了这些变量的环境的表达式(通常是一个函数),因而这些变量也是该表达式的一部分。
我认为闭包就是能够读/写函数内部的某些变量的子函数,并将这些变量保存在内存中.
闭包的作用
上面的概念中已经提到过,主要就是为了读/
写函数内部的某些变量,并将它保持在内存中.可能这样讲未必这么容易理解,下面让我们来看一些例子:
1,读取警察的生命值
function PoliceMan() {
//定义初始生命值
var lifeEnergy = 100;
//显示当前生命值
function showLifeEnergy() {
alert(lifeEnergy);
}
return showLifeEnergy;
}
//创建一个警察
var pm = new PoliceMan();
//显示当前生命值
pm();

2,读写/保存 警察的生命值
function PoliceMan() {
//定义初始生命值
var lifeEnergy = 100;
//中弹减少生命值
InBullet = function(){
lifeEnergy -= 1;
}
//显示当前生命值
function showLifeEnergy() {
alert(lifeEnergy);
}
return showLifeEnergy;
}
//创建一个警察
var pm = new PoliceMan();
//显示当前生命值
pm();
//中弹减少生命值
InBullet();
//显示当前生命值
pm();

注意事项
由以上例子我们可以看到警察的生命值变量
lifeEnergy会一直驻留在内存当中.如果这种方法使用频繁,那么很容易就把机器的内存消耗完.因此建议能用函数的地方就尽量使用函数,而不要使用
闭包.
作者:肥占
出处:http://extjs.org.cn

本文版权归作者和ExtJs中文资讯站共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。


相关文档:

通过javascript获得url参数

页面提交数据一般有两种方法:get,post。post就是所谓的form提交,使用视图;get是通过url提交。
Get方法一般用后台代码(如asp,asp.net)获得参数,代码很简单:Request.QueryString["id"];即可获取。 
有些时候需要直接在前台获取url参数,要用到javascript,js没有直接获取url参数的方法,那么,我们如何通过js ......

[翻译]High Performance JavaScript(006)

Identifier Resolution Performance  标识符识别性能
    Identifier resolution isn't free, as in fact no computer operation really is without some sort of performance overhead. The deeper into the execution context's scope chain an identifier exists, the slower it is to access for ......

[翻译]High Performance JavaScript(007)

Dynamic Scopes  动态作用域
    Both the with statement and the catch clause of a try-catch statement, as well as a function containing eval_r(), are all considered to be dynamic scopes. A dynamic scope is one that exists only through execution of code and therefore cannot be det ......

[翻译]High Performance JavaScript(010)

Cloning Nodes  节点克隆
    Another way of updating page contents using DOM methods is to clone existing DOM elements instead of creating new ones—in other words, using element.cloneNode() (where element is an existing node) instead of document.createElement().
 &nbs ......

javascript继承方式之三

3、组合构造函数/原型方式写类,采用前面种方式继承
这种方式父类,子类的属性都挂在构造函数里,方法都挂在原型上。
/**
* 父类Polygon:多边形
*/
function Polygon(sides) {
this.sides = sides;
}
Polygon.prototype.setSides = function(s) {this.sides=s;}
/**
* Triangle 三角形
* @param {Object} b ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号