对象数学Javascript

Object mathematics Javascript

本文关键字:Javascript 对象      更新时间:2023-09-26

我在JavaScript中的对象遇到了一些问题。请遵守以下代码:

function Bullet(x, y) {
    this.x = x;
    this.y = y;
    console.log(this.x);
    this.fire = function() {
        this.x++;
        console.log(this.x);
    };
    this.draw = function(ctx, bulletImage) {
        ctx.drawImage(bulletImage, this.x, this.y);
    };
};

问题出在 this.fire((;我正在尝试做的是从我的主脚本运行它:

bullet = new Bullet(20, 80);
bullet_loop = setInterval(bullet.fire, 11);

然后它应该执行 this.fire(); 函数,直到我取消间隔。然而,这按计划进行。

创建对象时,它具有行console.log(this.x);这将按原样返回"20",但是当调用this.fire();函数时它应该将1加起来最多this.x,就像您在发出this.x++;时所期望的那样。但是,当它到达this.fire();函数中的console.log(this.x);行时它返回NaN .

有人知道我在这里做错了什么吗?

回调未正确绑定。 最简单的方法是将命令包装在函数中:

bullet_loop = setInterval(function() { bullet.fire(); }, 11);

您还可以使用Function.prototype.bind功能:

bullet_loop = setInterval(bullet.fire.bind(bullet), 11);