Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

闭包 Closure #13

Open
39Er opened this issue May 17, 2017 · 0 comments
Open

闭包 Closure #13

39Er opened this issue May 17, 2017 · 0 comments

Comments

@39Er
Copy link
Owner

39Er commented May 17, 2017

什么是Closure

wikipedia:

In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.

MDN:

闭包是指这样的作用域,它包含有一个函数 ,这个函数可以调用被这个作用域所封闭的变量、函数或者闭包等内容。通常我们通过闭包所对应的函数来获得对闭包的访问。

通俗的讲:

闭包就是一个能够访问外部变量的函数

在JS中,每个function都是闭包,因为它总是能访问在它外部定义的数据。

Closure 样例

var generateClosure = function() {
	var count = 0;
	var get = function() {
		count ++;
		return count;
	};
	return get;
};
var counter = generateClosure();
console.log(counter()); // 输出 1
console.log(counter()); // 输出 2
console.log(counter()); // 输出 3

这段代码中, generateClosure() 函数中有一个局部变量count, 初值为 0。还有一个叫做 get 的函数, get 将其父作用域,也就是 generateClosure() 函数中的 count 变量增加 1,并返回 count 的值。 generateClosure() 的返回值是 get 函数。在外部我们通过 counter 变量调用了generateClosure() 函数并获取了它的返回值,也就是 get 函数,接下来反复调用几次 counter(),我们发现每次返回的值都递增了 1。

按照通常命令式编程思维的理解, count 是generateClosure 函数内部的变量,它的生命周期就是 generateClosure 被调用的时期,当 generateClosure 从调用栈中返回时, count 变量申请的空间也就被释放。问题是,在 generateClosure() 调用结束后, counter() 却引用了“已经释放了的” count变量,而且非但没有出错,反而每次调用 counter() 时还修改并返回了 count。

这正是所谓闭包的特性。当一个函数返回它内部定义的一个函数时,就产生了一个闭包,闭 包 不 但 包 括 被 返 回 的 函 数 , 还 包 括 这 个 函 数 的 定 义 环 境 。 上 面 例 子 中 ,当函数generateClosure() 的内部函数 get 被一个外部变量 counter 引用时, counter和generateClosure() 的局部变量就是一个闭包。

闭包用途

  1. 实现私有成员;
  2. 避免全局变量污染;
  3. 使一个变量常驻内存中

注:由于IE的js对象和DOM对象使用不同的垃圾收集方法,因此闭包在IE中会导致内存泄露问题,也就是无法销毁驻留在内存中的元素

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant