cocos creator 2.4 node.on node.off 关闭监听

cocos creator 2.4 node.on node.off

this.node.on("test1",this.testFunc2,this);
this.node.off("test1",this.testFunc2,this);

回调函数这样写能关掉监听


this.node.off("test1",function(){
this.testFunc2();
},this);

this.node.off("test1",function(){
this.testFunc2();
},this);

这样写却不能,这是为什么

写成箭头函数的形式也不行

this.node.on("test1",()=>{
            this.testFunc2();
        },this);
this.node.off("test1",()=>{
            this.testFunc2();
        },this);

该回答引用GPTᴼᴾᴱᴺᴬᴵ
第二种写法不能正常关闭监听是因为在 node.off 中传入的函数是一个匿名函数,与添加监听时传入的匿名函数不是同一个函数对象,所以无法正确地关闭监听。

可以修改第二种写法,将匿名函数改为命名函数,这样在关闭监听时可以传入同一个函数对象,从而正确地关闭监听,例如:

function callback() {
    this.testFunc2();
}
this.node.off("test1", callback, this);


或者使用箭头函数,例如:

this.node.off("test1", () => {
    this.testFunc2();
}, this);


这样可以保证在添加监听和关闭监听时传入的是同一个函数对象,从而能够正确地关闭监听。