js解除绑定事件的问题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text">
<script>
    var input = document.querySelector('input');
    input.addEventListener('input',aaa,false)
    function a(e) {
        setTimeout(function () {
            b(e);
        },200)
    }
    function b(e) {
        input.removeEventListener('input',aaa,false);
    }

    function aaa(e) {
        console.log(e.target.value);
        a(e);
    }
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text">
<script>
    var input = document.querySelector('input');
    input.addEventListener('input',aaa.bind(this),false)
    function a(e) {
        setTimeout(function () {
            b(e);
        },200)
    }
    function b(e) {
        input.removeEventListener('input',aaa.bind(this),false);
    }

    function aaa(e) {
        console.log(e.target.value);
        a(e);
    }
</script>
</body>
</html>

上面两个代码为什么一个可以解除DOM的绑定的事件,一个不可以,原因出现在bind这个函数,我想知道为什么bind(this)就不能实现这个功能呢????

阅读 2.9k
2 个回答

每次 bind() 都会生成一个新的函数返回出来,所以 a.bind(o) !== a.bind(o)

新手上路,请多包涵

每次使用bind都会返回一个函数对象,你在add和remove中两次使用bind返回了两个不同的函数对象,所以无法取消事件绑定。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题