[問題] addEventListener中的this

看板Ajax作者 (不是開玩笑的)時間9年前 (2015/04/19 12:56), 編輯推噓2(203)
留言5則, 3人參與, 最新討論串1/1
想請問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://www.ptt.cc/bbs/Ajax/M.1429419418.A.A92.html

04/19 13:59, , 1F
.call 跟 .apply 可以改變 function 的 this
04/19 13:59, 1F

04/19 14:00, , 2F
不過這邊是 spec 裡規定 this 指向觸發事件的元素
04/19 14:00, 2F

04/19 14:00, , 3F
04/19 14:00, 3F

04/20 11:37, , 4F
原來是spec規定的,晃然大悟了! 感謝
04/20 11:37, 4F

04/24 10:41, , 5F
可以用 bind
04/24 10:41, 5F
文章代碼(AID): #1LCpMQgI (Ajax)