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

在JavaScript类事件监听器中调用方法报method not defined错误如何解决

问题原因

  • 类的实例方法必须通过实例对象访问,你在事件回调内直接写getClickPosition会被识别为全局函数,自然不存在
  • 你给事件监听传入的是普通匿名函数,普通函数的this默认指向触发事件的canvas DOM元素,不是Game类的实例,就算写this.getClickPosition也无法正确访问到方法
  • getClickPosition内直接使用了全局event而不是传入的参数e,部分浏览器不支持全局event对象,会额外报错

修复代码

class Game {
    constructor(canvas) {
        this.canvas = canvas;                        
        // 用箭头函数保持this指向Game实例
        this.canvas.addEventListener('mousedown', (e) => {
            // 通过this调用实例方法
            this.getClickPosition(this.canvas, e)
        })
    }

    getClickPosition(canvas, e) {
        const rect = canvas.getBoundingClientRect()
        // 使用参数e而不是全局event
        const x = e.clientX - rect.left
        const y = e.clientY - rect.top
        console.log("x: " + x + " y: " + y)
    }
}
const canvas = document.querySelector('canvas')
const game = new Game(canvas)

可选替代方案

如果不想用箭头函数,也可以通过bind手动绑定回调的this指向:

this.canvas.addEventListener('mousedown', function (e) {
    this.getClickPosition(this.canvas, e)
}.bind(this))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:45:00