我正在处理 Javascript“类”,并且我有一个具有正确绘制方法的桨,但由于某种原因,我的 moveBall 函数被搞砸了。谁能指出为什么?我收到一条错误消息,指出 moveBall() 不是函数。
编辑:我包含了更多代码,我调用 init() 来启动它。
class Ball {
constructor(x, y, r, sAngle, rAngle) {
this.x = x;
this.y = y;
this.r = r;
this.sAngle = sAngle;
this.rAngle = rAngle;
this.speed = null;
}
drawBall() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, this.sAngle, this.rAngle);
ctx.fillStyle = "#FF0000";
ctx.fill();
}
moveBall() {
this.x += this.speed;
}
}
function init() {
var ball = new Ball(c.height / 2, c.width / 2, 10, 0, 2 * Math.PI);
var paddleLeft = new Paddle(0, 0, 20, 100);
ball.ballPhysics = 1.0;
draw(ball, paddleLeft);
main(ball);
}
window.main = function (ball) {
window.requestAnimationFrame(main);
ball.moveBall();
window.onload = function () {
document.addEventListener('keydown', function (event) {
if (event.keyCode === 65) {
}
}, false);
}
};
最佳答案
如果您像 Ball.moveBall() 这样使用它,那么它是不正确的,您必须首先实例化 Ball 类或使用像这样的静态方法
class A {
static f() {
}
}
然后调用
A.f();
否则检查下面的片段
class Ball {
constructor(x, y, r, sAngle, rAngle) {
this.x = x;
this.y = y;
this.r = r;
this.sAngle = sAngle;
this.rAngle = rAngle;
this.speed = null;
}
drawBall() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, this.sAngle, this.rAngle);
ctx.fillStyle = "#FF0000";
ctx.fill();
}
moveBall() {
this.x += this.speed;
}
}
var greenBall = new Ball(0, 0 , 10, 0, 0);
greenBall.speed = 5;
greenBall.moveBall();
document.write(greenBall.x);
关于javascript - ES6 类方法不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36050199/