作者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/cn.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