ES6 类方法不是函数

ES6 class methods not a function

本文关键字:函数 类方法 ES6      更新时间:2023-09-26

我正在搞乱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);

确保在你尝试运行的代码范围内有一个 ball 实例,并尝试var moveball = function(){this.x += this.speed; };看看它是否是一个编译问题,并确保你像ball.moveball()一样访问它

您可以定义main以接受参数ball。但是你从不调用main,所以你不能向它传递参数。

虽然window.requestAnimationFrame(main);会调用该函数,但它不会向其传递任何内容。

您似乎要引用在 init 中定义的ball变量。在这种情况下,请从函数定义中删除参数ball,以便它不会隐藏该变量:

window.main = function() { ... };

你也不想在main内部分配给window.onload,因为这不会一遍又一遍地发生。