作者nohaha (不是開玩笑的)
看板Ajax
標題[問題] addEventListener中的this
時間Sun Apr 19 12:56:55 2015
想請問anonymous function中的 this指向root element(window)
這個規則是固定的嗎
我在chrome測試下面的code
var btn = document.getElementById('myBtn');
btn.addEventListener('click', function(){
console.log(this === btn);
},false);
其中event handler是以anonymous function的方式給值的
預期應該是false,但會顯示為true,
想知道我的觀念是錯在那邊了
謝謝大家
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.250.193.25
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Ajax/M.1429419418.A.A92.html
1F:推 s25g5d4: .call 跟 .apply 可以改變 function 的 this 04/19 13:59
2F:→ s25g5d4: 不過這邊是 spec 裡規定 this 指向觸發事件的元素 04/19 14:00
4F:→ nohaha: 原來是spec規定的,晃然大悟了! 感謝 04/20 11:37
5F:推 SansWord: 可以用 bind 04/24 10:41