闭包:是延长局部变量的生命周期
闭包的作用:返回的是一个函数而不是一个结果。
如以下例子:
<html>
<head>
</head>
<body>
<h1 id="myHeader">click here</h1>
</body>
<script type="text/javascript">
init();
function init()
{
//必须放在这,如果放在head中的话,就会说找不到myHeader节点
document.getElementById("myHeader").onclick = test(33);
function test(index){
return function(){
alert(index);
}
}
以上解决了js dom动态添加事件的时候传递参数的方法
事件响应方法:
function test(index){
return function(){
alert(index);
}
}