我在解决一些范围问题时遇到了一些麻烦。我正在使用一个类方法在 Canvas 上绘制一个正方形,并想使用另一个类方法来移动它,但似乎我无法传递上下文...
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
}
}
上下文被传递到代码中的 User 类中,如下所示 in this pen但据我所知,它传递给 User 类的方式不是问题,这是我在 move 函数中访问它的方式。
我也尝试在构造函数中为上下文定义一个独立于 this
的变量,但这也没有成功。
最佳答案
您必须绑定(bind)您的方法。 ES6 classes doesn't do that automatically.
在你的构造函数中尝试添加这一行:
this.move = this.move.bind(this);
关于javascript - 使用类方法在 HTML5 Canvas 上绘图 : scope problems (JS, ES6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41169190/