您的位置:首页 > Web前端 > JavaScript

[ javascript ] javascript闭包测试!

2013-01-16 17:40 183 查看
<!DOCTYPE html PUBLIC "-//W4C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>title</title>
<script type = "text/javascript" src = "js/jquery-1.7.1.js"></script>
<script  type = "text/javascript">
$(function(){
$("#id1").click(function(){
alert("al");
});
$("#id2").click(function(){
alert("a2");
});
$("#id3").click(function(){
alert("a3");
});
$("#id4").click(function(){
alert("a4");
});

//每次传入的值都是不一样的,但是n依然存在,每次都是1
//但是这里的 test2()。只被执行了一次。
//在var t = test2();之后就不在执行了。
//正常来说,函数执行完毕之后,其中的局部变量是会自动销毁的。( 至少java是这样干的,不是么?)
//那么下面的三个函数,依旧执行,继续可以访问n的值,这就说明了,n一直是存在的。
//一直存在内存中,并没有销毁。
//我想这里的t应该就是所谓的闭包吧。
//那么这样的话,它不自动销毁,那么它何时销毁呢?
//如果我不清理它,它是否一直在内存中?
$("#id5").click(function(){
alert("a5");
var t = test2();
t(1);
t(11);
t(12);
});

//这个的test(),返回了inner函数。
$("#id6").click(function(){
alert("a6");
var t = test();
t();

});

function test(){
alert("test");//在var t = test(); 时执行
function inner(){
alert("inner");
}

return inner;
}

function test2(){
var n = 1;
alert("n" + n);
function add(a){
alert(a + n);
}
return add;
}
});
</script>
</head>
<body>
<input value = "login" type = "button" id = "id1"/>
<input value = "login" type = "button" id = "id2"/>
<input value = "login" type = "button" id = "id3"/>
<input value = "login" type = "button" id = "id4"/>
<input value = "login" type = "button" id = "id5"/>
<input value = "login" type = "button" id = "id6"/>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: