ES6 class methods not a function
Solution 1
If you are using it like Ball.moveBall() than it's incorrect, you must instantiate Ball class first or use static methods like
class A {
static f() {
}
}
and call like
A.f();
otherwise check the snippet below
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);
Solution 2
You define main
to accept an argument ball
. But you are never calling main
, so you cannot pass an argument to it.
While window.requestAnimationFrame(main);
will call the function, it won't pass anything to it.
It seems you want to refer to the ball
variable that is defined inside init
. In that case, remove the parameter ball
from the function definition so that it doesn't shadow that variable:
window.main = function() { ... };
You also don't want to assign to window.onload
inside main
, because that wouldn't happen over and over again.
Solution 3
make sure you have an instance of ball in the scope of the code you are trying to run, and try var moveball = function(){this.x += this.speed; };
to see if it's a compile issue, and make sure you are accessing it like ball.moveball()
Cowmoogun
Updated on June 26, 2022Comments
-
Cowmoogun almost 2 years
I'm messing around with Javascript "classes" and I have a paddle that has a proper method to draw, but for some reason my moveBall function is messed up. Could anyone point out why? I get an error saying that moveBall() is not a function.
Edit: I included some more code, I call init() to start it all.
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); } };