JS 函数(5)—闭包

闭包

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

 

理解闭包

闭包是指有权访问另一个函数的作用域中的变量的函数。

创建闭包的常见方式,就是在一个函数内部创建另一个函数。

 

闭包——是指函数体内的变量可以隐藏于作用域链之间,看起来是函数将变量包裹起来。

 

当一个函数嵌套了另一个函数,外部函数将内部函数作为值返回。

 

产生闭包效果的环境必须是嵌套函数的引用被保存到了一个全局作用域里面。

 

普通的函数内嵌,内部函数先执行;而闭包则是,先把内部函数赋给外部函数,然后再执行。

 

闭包的两个作用:读取函数内部的变量,让这些变量的值始终保存在内存中。

 

This is an example of lexical scoping: in JavaScript, the scope of a variable is defined by its location within the source code (it is apparent lexically) and nested functions have access to variables declared in their outer scope.

 

闭包与变量

由于作用域链的机制,闭包中所保存的是整个外部函数的变量对象;所以闭包只能取得外部函数中变量的最后一个值。

比较下面两个函数:

函数1:

1 function createFunctions() {
2     var result = new Array();
3     for(var i = 0; i < 10; i++) {
4         result[i] = function() {
5             return i;
6         };
7     }
8     return result; 
9 }

函数2:

 1 function createFunctions() {
 2     var result = new Array();
 3     for(var i = 0; i < 10; i++) {
 4         result[i] = function(num) {
 5             return function(num) {
 6                 return num;
 7             };
 8         }(i);
 9     };
10     return result;
11 }

有待补充。。。

 

模仿块级作用域

函数声明:

1 (function foo() {
2     //块级作用域
3 })();

 

函数表达式:

1 var foo = function() {
2     //块级作用域
3 }();

 

无论什么时候,只要临时需要一些变量,就可以使用私有作用域。

1 (function() {
2     var now = new Date();
3     if(now.getMonth() === 0 && now.getDate() === 1) {
4         alert("Happy New Year!");
5     }
6 })();

 

posted @ 2016-07-29 11:19  Aaron_Xiao  阅读(215)  评论(0)    收藏  举报