为了账号安全,请及时绑定邮箱和手机立即绑定

无法读取javascript中未定义的属性“clearRect”

无法读取javascript中未定义的属性“clearRect”

皈依舞 2023-11-02 21:14:36
我看到这个问题以前被问过,但它并没有解决我的问题!我是 JavaScript 新手,我几乎花了一天时间尝试解决它,但仍然无法解决。我有一个这样的类和函数:let playerTank = {width: 80, height: 80, speed: 2};class Tank {    constructor(canvas) {        this.canvas = canvas;        this.ctx = canvas.getContext("2d");    }    draw() {        this.ctx.drawImage(.....);        this.ctx.stroke();    }    update(e) {        if (e.keyCode == 37) {            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);            this.draw();            // do something ...        }    }}function main() {    let canvas = document.getElementByID("my-canvas");        let tank = new Tank(canvas);    tank.draw();    window.addEventListener("keydown", tank.update, true);    window.addEventListener("keyup", tank.update, false);}main();这是我的问题!当我单击该键时,我会收到以下错误:can't read property 'clearRect' of undefinedcan't read property 'draw' of undefined我实在不明白为什么不能访问同一个类中的属性和函数?
查看完整描述

1 回答

?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

你失去了上下文:


class Tank {

    draw() {

      console.log('draw');

    }

    update() {

       this.draw();

    }

}


const tank = new Tank();


// Call method of instance. Works

tank.draw(); 


// Set this method as listener. 

// Dont works, cause method called from event context (window)

window.addEventListener("event1", tank.update, true); 


// Set anonimous listener, which call method. Works

window.addEventListener("event2", () => tank.update(), true); 


// Set method as listener and bind right context. Also works

window.addEventListener("event3", tank.update.bind(tank), true); 


window.dispatchEvent(new Event("event1"));

window.dispatchEvent(new Event("event2"));

window.dispatchEvent(new Event("event3"));


查看完整回答
反对 回复 2023-11-02
  • 1 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信