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

我看到这个问题以前被问过,但它并没有解决我的问题!我是 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 undefined

can't read property 'draw' of undefined

我实在不明白为什么不能访问同一个类中的属性和函数?


皈依舞
浏览 118回答 1
1回答

蝴蝶刀刀

你失去了上下文:class Tank {    draw() {      console.log('draw');    }    update() {       this.draw();    }}const tank = new Tank();// Call method of instance. Workstank.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. Workswindow.addEventListener("event2", () => tank.update(), true); // Set method as listener and bind right context. Also workswindow.addEventListener("event3", tank.update.bind(tank), true); window.dispatchEvent(new Event("event1"));window.dispatchEvent(new Event("event2"));window.dispatchEvent(new Event("event3"));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript