【问题标题】:Phaser 3 - How to reference the object itself from within arrow functions events?Phaser 3 - 如何从箭头函数事件中引用对象本身?
【发布时间】:2021-08-10 18:00:12
【问题描述】:

我有这样的场景,我动态地创建了 5 个按钮并向其加载自定义属性(mydata):

create() {
    for (var a=1; a<=5; a++) {
        this.mybutton = this.add.image(a*50, 10, '').setInteractive();
        this.mybutton.mydata = a;
        this.mybutton.on('pointerup', (e) => {
           // how to return mydata property value??
        });
    }
}

我在网上发现 e.targete.currentTarget 可以提供帮助,但在这种情况下,两者都返回 undefined。

不管怎样,知道箭头函数将 this 移动到父作用域,还有办法在事件中引用对象本身并检索其属性吗?

PS:我知道使用常规函数可以达到预期的效果,但我现在正在研究箭头函数,所以我有点“喜欢它”,然后我想知道是否有以这种特殊的方式周转。

谢谢!

编辑 - 我结束了解决方案:

create() {
    for (let a=1; a<=5; a++) {
        const mybutton = this.add.image(a*50, 10, '').setInteractive();
        mybutton.mydata = a;
        mybutton.on('pointerup', (e) => {
           console.log (mybutton); // returns the object
           console.log (mybutton.mydata); // returns the property
        });
    }
}

【问题讨论】:

    标签: javascript dom-events this phaser-framework arrow-functions


    【解决方案1】:

    对我来说,当前目标工作正常

    $('#test').on("pointerup", (e) =>
    {
        console.log(e.currentTarget);
    });
    

    https://jsfiddle.net/afnoLtb2/1/

    【讨论】:

      猜你喜欢
      • 2021-01-04
      • 2013-02-02
      • 1970-01-01
      • 2019-01-27
      • 2016-08-11
      • 1970-01-01
      • 2018-02-07
      相关资源
      最近更新 更多