前端 - 关于javascript的bind方法的疑问
本文介绍了前端 - 关于javascript的bind方法的疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
按照我的理解,函数后面执行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执行的
<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的
这篇关于前端 - 关于javascript的bind方法的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文