前端 - 关于javascript的bind方法的疑问
怪我咯
怪我咯 2017-04-11 11:58:35
[JavaScript讨论组]

按照我的理解,函数后面执行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呢,求解答。

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(4)
天蓬老师

chrome执行的

<html>
<head>
</head>
<body>
<p id="testId" style="background-color:red;width:200px;height:200px"></p>

<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>
<p id="testId" style="background-color:red;width:200px;height:200px"></p>

<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>

所以你不管是点击当前 p 还是直接点击页面任何地方,this 都是绑在 p 元素的 context的

PHP中文网

这不可能,bind应该是window,请贴出上下文代码。

=======后更新

因为题主的代码document.getElementById("testId")null导致了this指向window

ringa_lee

本地 chrome 测试了下,没问题啊。。

题主是啥浏览器?

迷茫
window.addEventListener('click', function(event) {
     console.log(this);//这里的this就是window
}.bind(null));
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号