什么是闭包

136 阅读2分钟

1.闭包的定义(MDN)

A closure is the combination of a function bundled together (enclosed) with references to its surrounding
state (the lexical environment). In other words, a closure gives you access to an outer function’s scope
from an inner function. In JavaScript, closures are created every time a function is created, at function
creation time.
闭包是一个函数绑定在一起(附在一起)和它周围状态(词汇环境)的引用的组合。换句话说,闭包可以从内部函数访问外部函数的范
围。在JavaScript中,每次创建函数时,都会在函数创建时创建闭包

其他版本
Closures are functions that refer to independent (free) variables (variables that are used locally, but
defined in an enclosing scope). In other words, the function defined in the closure 'remembers' the
environment in which it was created.
闭包是指独立(自由)变量(本地使用但在封闭范围内定义的变量)的函数。换句话说,闭包中定义的函数“记住”创建它的环境

A closure is a special kind of object that combines two things: a function, and the environment in which
that function was created. The environment consists of any local variables that were in-scope at the time
that the closure was created
闭包是一种特殊的对象,它结合了两个方面:一个函数和创建该函数的环境。环境由创建闭包时在范围内的任何局部变量组成

2.自己的理解

闭包是一种特殊的环境,内部函数访问外部函数中的变量所形成的一个环境

3.传统函数的机理

普通函数自身是没有状态的(stateless),它们所使用的局部变量都是保存在函数调用栈(Stack)上,随着函式调用的结束、退出,这些临时保存在栈上的变量也就被清空了,所以普通函式是没有状态、没有记忆的。

var inc = function () {
  var count = 0;
  return ++count;
};

inc(); // return: 1
inc(); // return: 1

因为这里的 count 只是一个普通函数的局部变量,每次执行函式时都会被重新初始化(被第一条语句清零),它不是下面例子中可以保持状态的闭包变量。

function foo(){
  var a = 2;
  function bar(){
    console.log(a);
  }
  return bar;
}
var baz = foo();
baz();//2--函数中的变量被访问到了,这就是闭包的作用。

在一般情况下,foo();函数在执行后-立即调用的函数表达式(IIFE),内部作用域会被销毁,这是由于引擎的垃圾回收机制在释放不需要的内存空间。而闭包则会阻止函数在执行后内部作用域被销毁。

4.闭包的用途

  1. 读取函数内部的变量
  2. 让这些变量始终保存在内存中,不会由于函数的调用而被销毁