• 32.闭包的理解2


     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4     <meta charset="utf-8">
     5     <title>闭包的理解2</title>
     6 </head>
     7 <body>
     8 
     9 <p>局部变量计数</p>
    10 <button onclick="tom()">计数</button>
    11 <p id="demo">0</p>
    12 <script>
    13 
    14     function add() {
    15         var counter = 0;
    16         return counter += 1;
    17     }
    18 
    19     function tom(){
    20         document.getElementById("demo").innerHTML = add();
    21         //一直都是1,因为counter是局部变量。要想实现递增的效果,counter必须是全局变量,或者用闭包
    22     }
    23 </script>
    24 
    25 </body>
    26 </html>
    View Code 1
     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4     <meta charset="utf-8">
     5     <title>闭包</title>
     6 </head>
     7 <body>
     8 
     9 <p>局部变量计数-闭包。</p>
    10 <button  onclick="tom()">计数</button>
    11 <p id="demo">0</p>
    12 <script>
    13     var add = function () {
    14         var counter = 0;
    15         return function () {return counter += 1;}
    16     };
    17     var result=add();
    18 
    19     function tom(){
    20         document.getElementById("demo").innerHTML = result();//递增
    21     }
    22 </script>
    23 
    24 </body>
    25 </html>
    View Code 2
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>闭包的理解2</title>
    </head>
    <body>

    <p>局部变量计数</p>
    <button onclick="tom()">计数</button>
    <p id="demo">0</p>
    <script>

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

    function tom(){
    document.getElementById("demo").innerHTML = add();
    //一直都是1,因为counter是局部变量。要想实现递增的效果,counter必须是全局变量,或者用闭包
    }
    </script>

    </body>
    </html>

  • 相关阅读:
    vijos1746 floyd
    总结
    用javascript代码拼html
    异步编程学习
    SELECT
    设计 Azure SQL 数据库,并使用 C# 和 ADO.NET 进行连接
    H2数据库
    ASP.NET 文档
    ASP.NET MVC
    ASP.NET Core 中的 Razor 页面介绍
  • 原文地址:https://www.cnblogs.com/mx2036/p/6924405.html
Copyright © 2020-2023  润新知