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>
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>
<!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>