function animal(type, name) {
var count = 0;
this.type = type;
this.name = name;
this.test = function () { alert(this.type) }
staticFunc = function () {
count++;
alert(count);
}
return staticFunc;
}
animal.prototype.alertAnimalType = function () {
alert(this.type);
}
var n = animal("a", "b");
n();
var count = 0;
this.type = type;
this.name = name;
this.test = function () { alert(this.type) }
staticFunc = function () {
count++;
alert(count);
}
return staticFunc;
}
animal.prototype.alertAnimalType = function () {
alert(this.type);
}
var n = animal("a", "b");
n();
n();
闭包的定义非常晦涩——闭包,是指语法域位于某个特定的区域,具有持续参照(读写)位于该区域内自身范围之外的执行域上的非持久型变量值能力的段落。这些外部执行域的非持久型变量神奇地保留它们在闭包最初定义(或创建)时的值(深连结)。简单来说,闭包就是在另一个作用域中保存了一份它从上一级函数或作用域取得的变量(键值对),而这些键值对是不会随上一级函数的执行完成而销毁。周爱民说得更清楚,闭包就是“属性表”,闭包就是一个数据块,闭包就是一个存放着“Name=Value”的对照表。就这么简单。但是,必须强调,闭包是一个运行期概念。
在Javascript中闭包(Closure),有两个特点:
- 作为一个函数变量的一个引用 - 当函数返回时,其处于激活状态。
- 一个闭包就是当一个函数返回时,一个没有释放资源的栈区。