1. 程式人生 > >js中的閉包實現自增

js中的閉包實現自增

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>測試</title>
<script type="text/javascript"> 
function f(x) { 
var a = 0; 
a++; 
x++; 
var inner = function() { 
return a + x; 

return inner; 

//var test = f(1); 
</script> 
<script type="text/javascript">
function testTime(){
var date1 = new Date();
var m;
for(var i=0;i<10000;i++){
m = i;
}
var date2 = new Date();
for(var i=9999;i>=0;i--){
m = i;
}
var date3 = new Date();
console.log(date2-date1);
console.log(date3-date2);
test1.value=date2-date1;
test2.value=date3-date2;
}
var v=0;
function test(){
incrementText.value=v++;
}
//js閉包實現自增
function incrementClosure(){
// var i = incrementText.value;
var i = 0;
function increment(){
i++;
   return i;
}
return increment;
}
var textValue = incrementClosure();
function testClosure(obj){
//var textValue = incrementClosure();
incrementText.value = textValue();
}
</script>
</head>
<body>
<input type="button" value="測試for迴圈時間" onclick="testTime()"/>
<input type="text" id="test1"/>
<input type="text" id="test2"/><br/><br/>
<input type="button" value="測試" onclick="test()"/><br/><br/>
<input type="button" value="測試js閉包" onclick="testClosure(this)"/>
<input type ="text" id="incrementText"/>
</body>
</html>