js--dom--什么是闭包

来源:互联网 发布:python 期货量化交易 编辑:程序博客网 时间:2024/06/08 11:37

闭包:是延长局部变量的生命周期

闭包的作用:返回的是一个函数而不是一个结果。

如以下例子:

<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);
    }
}

执行结果:33
原创粉丝点击