Phaser 3中能否在dragstart事件内调用自定义函数?
问题原因与解决方案
你遇到的报错是因为普通function回调里的this指向不是你的游戏类实例,而是Phaser的Input对象,所以找不到getOtherCards方法。当然可以在此处调用自定义函数,调整this指向即可,以下是三种常用方案:
方案1:使用箭头函数(最推荐)
箭头函数不会创建自己的this,它会继承外层作用域的this(也就是你的游戏类实例),直接替换回调函数即可:
this.input.on('dragstart', (pointer, card) => { // 找出此牌堆中应一起移动的所有卡牌 this.getOtherCards(card); });
方案2:提前保存this到变量
在绑定事件前,把当前类实例的this存到一个变量里,回调里用这个变量调用方法:
const self = this; this.input.on('dragstart', function (pointer, card) { self.getOtherCards(card); });
方案3:用bind绑定this
通过bind方法手动把回调函数的this绑定到类实例:
this.input.on('dragstart', function (pointer, card) { this.getOtherCards(card); }.bind(this));
内容的提问来源于stack exchange,提问作者summer9844
相关产品推荐
相关产品推荐

