clearInterval.bind()不能作为传递给addEventListener的参数

时间:2016-04-29 18:14:23

标签: javascript

我想知道为什么clearInterval.bind不能作为传递到addEventListener函数的参数。模拟情况的简单例子。

HTML

<button id="start">Start</button>
<button id="end">End</button>
<div id="app"></div>

JS

var timer;
var i = 0;
document.getElementById('start')
    .addEventListener('click',function(){
       timer = setInterval(function(){
         document.getElementById('app').innerHTML = i
         i ++
    }, 1000)
},false)


document.getElementById('end')
    .addEventListener('click',clearInterval.bind(window,timer),false);

当我将clearInterval包围到下面的匿名函数中时,一切都按预期工作。

document.getElementById('end').addEventListener('click',function(){
    clearInterval.bind(window,timer)();
    // or just simple clearInterval(timer)
},false);

为什么不想工作?我错过了什么吗?

1 个答案:

答案 0 :(得分:4)

timer的值传递给bind。在代码运行时,值为undefined(因为您还没有点击 start )。所以你在新函数中绑定undefined

变量不会在JavaScript中通过引用传递。