按照我的理解,函数后面执行bind之后,函数里面的this就是bind方法传进入的bind了。但是在和事件结合的时候就遇到了问题,代码:window.addEventListener('click', function(event) { if (event.target.getAttribute('id') === 'testId') { // 这时候this是window,而不是document.getElementById("testId")
}
}.bind(document.getElementById("testId"))),为什么这是this是window而不是testId呢,求解答。
1 回答
小怪兽爱吃肉
TA贡献1852条经验 获得超1个赞
chrome执行的
<html><head></head><body><div id="testId" style="background-color:red;width:200px;height:200px"></div><script>window.addEventListener('click', function(event) { if (event.target.getAttribute('id') === 'testId') { // 这时候this是window,而不是document.getElementById("testId")
console.log( this === window ); // 输出 false
console.log( this === document.getElementById("testId") ); // 输出 true
}
}.bind(document.getElementById("testId")));</script></body></html>所以,当前 this 就是 document.getElementById("testId")
补充一点:
<html><head></head><body><div id="testId" style="background-color:red;width:200px;height:200px"></div><script>window.addEventListener('click', function(event) { if (event.target.getAttribute('id') === 'testId') { // 这时候this是window,而不是document.getElementById("testId")
console.log("if"); console.log( this === window ); // 输出 false
console.log( this === document.getElementById("testId") ); // 输出 true
}else{
console.log("else"); console.log( this === window ); // 输出 false
console.log( this === document.getElementById("testId") ); // 输出 true
}
}.bind(document.getElementById("testId")));</script></body></html>所以你不管是点击当前 div 还是直接点击页面任何地方,this 都是绑在 div 元素的 context的
添加回答
举报
0/150
提交
取消
