2016-04-29 71 views
0

我想知道爲什麼clearInterval.bind不能用作傳遞給addEventListener函數的參數。簡單的例子來模擬情況。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); 

爲什麼它不想工作?我錯過了什麼?

回答

4

timer的值傳遞給bind。在代碼運行時,值爲undefined(因爲您尚未點擊開始)。所以你在新函數中綁定undefined

變量未在JavaScript中通過引用傳遞。

+0

yeap,你是對的,我錯過了它 –

+1

@Quentin,你太快:)) – Rayon

相關問題