使用class方法借鉴HTML5Canvas:作用域问题(JS、ES6)

Using class methods to draw on HTML5 Canvas: scope problems (JS, ES6)

我在解决一些范围问题时遇到了一些麻烦。我正在使用 class 方法在 canvas 上绘制一个正方形,并想使用另一种 class 方法移动它,但似乎我无法传递上下文.. .

class User {
  constructor(user, x, y, ctx) {
    for (let metric in user) { this[metric] = user[metric]; }
    this.initialX = x;
    this.initialY = y;
    this.x = x;
    this.y = y;
    this.ctx = ctx;
    this.draw(this.initialX, this.initialY, this.ctx);
   }

  draw(x, y, ctx) {
    ctx.fillStyle = 'white';
    ctx.fillRect(x,y,20,20);
  }

  move(e) {
    //// stuff about motion goes here
     console.log(e.key, this.ctx); //// can't access `ctx` - the user key shows up in the console but the context is nowhere to be seen
     //// eventually this needs to be draw(x, y, ctx) that's passed back up to the draw function
  }

}

上下文在代码中进一步传递给用户 class,如 in this pen 所示,但据我所知它被传递给用户的方式 class 是没问题,这是我在移动功能中访问它的方式。

我也曾尝试在构造函数中独立于 this 为上下文定义一个变量,但这也没有成功。

您希望事件侦听器函数中有四个参数 (e, x, y, ctx),但侦听器将收到 only one argument 事件。

您必须明确地将所有参数传递给您的处理程序才能使用它们或想出另一种方法来访问它们。

您必须绑定您的方法。 ES6 classes doesn't do that automatically.

在你的构造函数中尝试添加这一行:

this.move = this.move.bind(this);