javascript - ES6 类方法不是函数

标签 javascript html ecmascript-6

我正在处理 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/

相关文章:

javascript - Firebase 更新值的速度没有我想要的 Javascript 快

javascript - plotly.js 如何在悬停时更改 z 数据以在色标上显示 % 和 %

javascript - 应用过滤器后 jQuery 调整窗口大小

javascript - 减少 JavaScript 中的对象数组

javascript - ECMAScript 6 箭头函数

javascript - 使用 Javascript 操作行数据

javascript - 如何减少 Javascript 中 2 个表之间的差距

html - 响应式元素——拉伸(stretch)再堆叠

javascript - 加载更多 Action jquery

javascript - 从键数组访问对象的属性