You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

类成员typeof返回undefined?PIXI.js事件系统调用方法异常排查

问题原因与解决方案

这是this指向错误导致的——当你把test方法直接传给PIXI的事件系统时,事件触发时this会指向触发事件的PIXI对象(比如Sprite、Container这类元素),而不是你的DialogueChoice实例,所以访问this.integer自然拿不到实例属性,返回undefined。直接调用时this正常指向实例,因此没有问题。

解决方法有三种,任选其一即可:

1. 在构造函数里绑定this

在构造函数中把方法的this强制绑定到当前实例,之后再将绑定后的方法传给PIXI事件:

class DialogueChoice
{
    constructor(text, resultFunc)
    {
        this.integer = 25;
        // 绑定test方法的this到实例
        this.test = this.test.bind(this);
        ...
    }
    test()
    {
        console.log(typeof(this.integer))
    }
}

// 绑定事件时直接传处理后的this.test
pixiElement.on('click', dialogueChoiceInstance.test);

2. 用箭头函数作为事件回调

给PIXI事件传回调时使用箭头函数,箭头函数的this会继承外层作用域的this(也就是你的DialogueChoice实例):

// 假设dialogueChoiceInstance是你的类实例
pixiElement.on('click', () => dialogueChoiceInstance.test());

3. 用箭头函数定义类方法

直接把类中的test方法定义为箭头函数,这样方法的this会永久绑定到实例:

class DialogueChoice
{
    constructor(text, resultFunc)
    {
        this.integer = 25;
        ...
    }
    // 箭头函数定义方法,this始终指向实例
    test = () => {
        console.log(typeof(this.integer))
    }
}

// 绑定事件时直接传方法即可
pixiElement.on('click', dialogueChoiceInstance.test);

内容的提问来源于stack exchange,提问作者Gaming Gecko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 09:57:19