闭包的理解

<!--
 * @Author: your TM_cc
 * @Date: 2021-11-01 18:43:44
 * @LastEditTime: 2021-11-03 20:47:15
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \闭包.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        /* 闭包可以让你从内部函数访问外部函数作用域 */
        function show() { //让变量一直保存到内存中
            let n = 1
            return function sum(){
                console.log(++n); //++n 先自增,后赋值 ; n++ 先赋值 后自增  --能够访问到sum函数外的作用域
            }
            sum();
        }
        let a = show(); // 执行show 开辟一个新区域 包含 n=1; sum ; 赋值给 a
        a();    // 执行a内的内容;调用sum 返回结果加1
        a();    // 由于show开辟的新区没有被释放 在此调用会在原有的基础上在此加1
    </script>
</body>
</html>

 

posted @ 2021-11-03 20:49  TM_cc  阅读(20)  评论(0)    收藏  举报