zoukankan      html  css  js  c++  java
  • Javascript闭包

    闭包严格地定义是由函数及其封闭的自由变量组成的集合体,这个定义是不是感觉晦涩那么懂,那么就先来看一个例子。

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

    在这段代码中,函数getCounter()中有一个局部变量 count,初值为0。还有一个叫 addCount() 的函数。addCount将父作用域getCounter()函数中的count变量加1,并返回count的值。getCounter()的返回值是addCount函数。在外部我们通过counter和counter1变量调用了getCounter()并获取了它的返回值,这样反复调用几次,我们发现每次返回值都增加了1。

    仔细分析一下上面的例子,按照我们习惯性的思维,count是函数getCounter()内部的变量,它的生命周期就是getCounter()函数被调用的时期,当函数getCounter()返回时,count变量申请的空间也就被释放。但是,事实并不是这样,在函数getCounter()调用结束后,counter和counter1还引用了count变量,而且非但没有出错,反而每次调用counter和counter1时还修改并返回了 count。这是怎么回事呢?

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

  • 相关阅读:
    1295. 统计位数为偶数的数字『简单』
    1281. 整数的各位积和之差『简单』
    697. 数组的度『简单』
    748. 最短完整词『简单』
    832. 翻转图像『简单』
    1446. 连续字符『简单』
    1455. 检查单词是否为句中其他单词的前缀『简单』
    1160. 拼写单词『简单』
    1304. 和为零的N个唯一整数『简单』
    1103. 分糖果 II『简单』
  • 原文地址:https://www.cnblogs.com/ay-a/p/9943211.html
Copyright © 2011-2022 走看看