JavaScript Closure

JavaScript variabler tillhör本地全局作用域。

全局变量能够通过Closure实现局部(私有)。

全局变量

函数能够访问函数内部定义的所有变量,比如:

Instance

function myFunction() {
    var a = 4;
    return a * a;
} 

Try it yourself

但是函数也能访问函数外部定义的变量,比如:

Instance

var a = 4;
function myFunction() {
    return a * a;
} 

Try it yourself

在最后这个例子中,a全局变量。

在网页中,全局变量属于 window 对象。

全局变量能够被页面中(以及窗口中)的所有脚本使用和修改。

在第一个例子中,a局部变量。

局部变量只能用于其被定义的函数内部。对于其他函数和脚本代码来说它是不可见的。

拥有相同名称的全局变量和局部变量是不同的变量。修改一个,不会改变其他。

不通过关键词 var 创建的变量总是全局的,即使它们在函数中创建。

变量的生命周期

全局变量活得和您的应用程序(窗口、网页)一样久。

局部变量活得不长。它们在函数调用时创建,在函数完成后被删除。

一个计数器的困境

假设您想使用变量来计数,并且您希望此计数器可用于所有函数。

您可以使用全局变量和函数来递增计数器:

Instance

// 初始化计数器
var counter = 0;
// 递增计数器的函数
function add() {
  counter += 1;
}
// 调用三次 add()
add();
add();
add();
// 此时计数器应该是 3

Try it yourself

上述解决方案有一个问题:页面上的任何代码都可以更改计数器,而无需调用 add()。

对于 add() 函数,计数器应该是局部的,以防止其他代码更改它:

Instance

// 初始化计数器
var counter = 0;
// 递增计数器的函数
function add() {
  var counter = 0; 
  counter += 1;
}
// 调用三次 add()
add();
add();
add();
//此时计数器应该是 3。但它是 0。

Try it yourself

它没有用,因为我们显示全局计数器而不是本地计数器。

通过让函数返回它,我们可以删除全局计数器并访问本地计数器:

Instance

// 递增计数器的函数
function add() {
  var counter = 0; 
  counter += 1;
  return counter;
}
// 调用三次 add()
add();
add();
add();
//此时计数器应该是 3。但它是 1。

Try it yourself

它没有用,因为我们每次调用函数时都会重置本地计数器。

JavaScript 内部函数可以解决这个问题。

JavaScript 嵌套函数

所有函数都有权访问全局作用域。

事实上,在 JavaScript 中,所有函数都有权访问它们“上面”的作用域。

JavaScript 支持嵌套函数。嵌套函数可以访问其上的作用域。

在本例中,内部函数 plus() 可以访问父函数中的 counter 计数器变量:

Instance

function add() {
    var counter = 0;
    function plus() {counter += 1;}
    plus();     
    return counter; 
}

Try it yourself

This can solve the counter dilemma if we can access it from the outside plus() Function.

We also need to find a function that only executes once counter = 0 Method.

We need closure (closure).

JavaScript Closure

Remember the self-invoking function? What will this function do?

Instance

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();
add();
add();
add();
// Counter is currently 3 

Try it yourself

Example explanation

Variable add Assignment is the return value of the self-invoking function.

This self-invoking function runs only once. It sets the counter to zero (0) and returns the function expression.

So add becomes a function. The most “exciting” part is that it can access the counter in the parent scope.

This is called JavaScript Closure. It allows the function to have “Private”Variable becomes possible.

The counter is protected by the scope of this anonymous function and can only be modified using the add function.

Closure refers to a function that has the right to access the parent scope, even after the parent function has closed.