# Closure

JavaScript 的作用域通俗来讲,就是指变量能够被访问到的范围(The range of variables that can be accessed)。分为全局作用域(Global scope)、函数作用域(Function scope)和块级作用域(Block scope)三种。

Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.

闭包其实就是一个可以访问其他函数内部变量的函数。All you need to know about closures is that when you have a function defined inside of another function that inner function has access to the variables and scope of the outer function. Even if the outer function finishes executing and those variables are no longer accessible outside that function.

# What is a Closure?

A closure is the combination of a function bundled together (enclosed) with reference 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.

Another thing to note is that if you define a function that uses global variables, this also produces a closure. The way closures work in JavaScript is that every scope has access to everything outside of its scope.

Generally, if the function referencing the closure is a global variable, then the closure will exist until the page is closed; but if the closure is no longer used, it will cause a memory leak.

The inner function will have access to the variables in the outer function scope, even after the outer function has returned.

# 闭包产生的原因

当前函数一般都会存在上层函数的作用域的引用,那么他们就形成了一条作用域链。闭包产生的本质就是:当前环境中存在指向父级作用域的引用

  1. 闭包的作用域链包含它自己的作用域、包含outer函数的作用域和全局作用域
  2. 通常,函数的作用域及其所有变量都会在函数执行结束后销毁
  3. 但是,当函数返回来了一个闭包,这个函数的作用域将一直在内存中保存在闭包不存在为止。

[1] 防抖 (opens new window)