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中文资讯站共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
相关文档:
功能:
重新加载文档。
语法:
location.reload(force)
参数:
force:可选参数,是一个布尔值。
如果省略参数,或者参数是false,它就会用HTTP头If-Modified-Since来检测服务器上的文档是否已改变。如果文档已改
变,reload()会再次下载该文档。如果文档未改变,则该方法将从缓存中 ......
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 ......
Nested Members 嵌套成员
Since object members may contain other members, it's not uncommon to see patterns such as window.location.href in JavaScript code. These nested members cause the JavaScript engine to go through the object member resolution process each time a dot is ......
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 ......
3、组合构造函数/原型方式写类,采用前面种方式继承
这种方式父类,子类的属性都挂在构造函数里,方法都挂在原型上。
/**
* 父类Polygon:多边形
*/
function Polygon(sides) {
this.sides = sides;
}
Polygon.prototype.setSides = function(s) {this.sides=s;}
/**
* Triangle 三角形
* @param {Object} b ......