zoukankan      html  css  js  c++  java
  • 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>

  • 相关阅读:
    091122杂记
    20100304我的碎碎念
    写给自己
    开始学习AGG
    找两个数组中的相同元素
    要多写代码了
    [翻译] AGG Reference 之 Basic Renderers(基础渲染器)
    在博客园日志中显示数学公式(旧,ASCIIMathML.js版说明)
    091128日志(博客园博客显示数学公式的方法!)
    与临时对象的斗争(上)
  • 原文地址:https://www.cnblogs.com/mx2036/p/6924405.html
Copyright © 2011-2022 走看看