游戏开发-cocos creator踩坑-bind(this)导致的事件监听off不掉

之前对js理解不够深入,用bind(this)做事件监听用的很爽,但是有一天发现下面这种类型的监听off关闭不掉

使用 off 关闭 事件时 失效
使用这样的方式 取消注册不会成功 
this.node.on("testEvent",this.refresh.bind(this)); 注册
this.node.off("testEvent",this.refresh.bind(this)); 取消注册

使用这样的方式才能成功
this.node.on("testEvent",this.refresh,this); 注册
this.node.off("testEvent",this.refresh.this); 取消注册

查询论坛发现是因为bind(this)产生了拷贝

this.node.on("testEvent",this.refresh.bind(this)); 
这里的回调函数
this.node.off("testEvent",this.refresh.bind(this)); 
和这里的回调函数

和真正的this.refresh,其实已经是3个函数了,所以如果需要off的,还是老实的用第三个传参this吧

原文地址:https://www.cnblogs.com/orxx/p/10941079.html