.bind()方法,js中addEventListener()与removeEventListener(),以及添加bind()指向无效问题

347 阅读1分钟

this.方法名().bind(this)

Function.prototype.bind=function(context){
    return this.apply(context,arguments)
   
}

apply、call、bind 三者相比较,之间又异同 何时用 apply、call,何时使用 bind 呢。:

var girl = {
    weight: 100,
}
var honghong = {
    getWeight: function() {
        return this.weight;
    }
}
 
console.log(honghong.getWeight.bind(obj)());  //100
console.log(honghong.getWeight.call(obj));    //100
console.log(honghong.getWeight.apply(obj));   //100

bind 多() 区别是,当你希望改变上下文环境之后并非立即执行,而是回调执行的时候,使用 bind() 方法。而 apply/call 则会立即执行函数

  • apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
  • apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文;
  • apply 、 call 、bind 三者都可以利用后续参数传参; bind是返回对应函数,便于稍后调用;apply 、call 则是立即调用 --------------------- 上面内容为查阅百度和csdn评论
1 this.mouseEvent = this.mouseEvent.bind(this)
2 window.addEventListener('mousedown', this.mouseEvent, {passive: true})
3 // window.addEventListener('mousedown', this.mouseEvent.bind(this), {passive: false})
4 // window.removeEventListener('mousedown', this.mouseEvent, {passive: false})
5 console.log(this.mouseEvent === this.mouseEvent) // --true
6 // console.log(this.mouseEvent.bind(this) === this.mouseEvent) // --false

function mouseEvent () {
    // ...
}

第三行是我一开始对鼠标操作事件添加的监听方法,打印第六行的时候是为false,后查阅相关资料发现,bind返回的是一个新的不同的函数,所以在使用.bind(this)处理的监听时候使用一个变量储存函数,当移除监听是使用该变量即可成功移除

console.error('若有错误,请指正,感谢批评')