按照我的理解,函数后面执行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呢,求解答。
本地 chrome 测试了下,没问题啊。。
题主是啥浏览器?
window.addEventListener('click', function(event) {
console.log(this);//这里的this就是window
}.bind(null));
这不可能,bind应该是window,请贴出上下文代码。
=======后更新
因为题主的代码document.getElementById("testId")
为null
导致了this
指向window
。
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的