Javascript setInterval 不适用于此。对象

标签 javascript class this setinterval move

<分区>

我在使用 Javascript 中的 setInterval() 方法时遇到问题。我的主要类(class):

var sq1 = new Square(20, 20);
window.onkeydown = function (e)
{
    var key = e.keyCode ? e.keyCode : e.which;
    if (key == 38)
    {
        sq1.moveUp();
    }
}

我有以下构造函数。

function Square(x,y)
{
    var multiplicator = 10;

    this.xPos = x;
    this.yPos = y;

    this.domObj = document.createElement("div");
    this.domObj.style.position = "absolute";
    this.domObj.style.left = this.xPos * multiplicator + 'px';
    this.domObj.style.top = this.yPos * multiplicator + 'px';
    this.domObj.style.width = multiplicator + 'px';
    this.domObj.style.height = multiplicator + 'px';
    this.domObj.style.backgroundColor = "black";
    document.getElementById("idCanvas").appendChild(this.domObj);

    this.moveUp = function ()
    {
        this.yPos--;
        this.domObj.style.top = (this.yPos * multiplicator) + 'px';
    }
}

现在一切正常,只需将每个 keyUp 事件向上 move 10px。 但是我想在 keyUp 事件之后每 1000 毫秒自动调用 this.moveUp()。 但是当我尝试这个时:

this.moveUp = function ()
{
    setInterval(function ()
    {
        this.yPos--;
        this.domObj.style.top = (this.yPos * multiplicator) + 'px';
    }, 1000);
}

我收到“this”为空的错误。

我该如何修复它(最好不用 jQuery)?

最佳答案

您需要将 setInterval 绑定(bind)到与您的类(class)相同的目标。

this.moveUp = function ()
{
    setInterval(function ()
    {
        this.yPos--;
        this.domObj.style.top = (this.yPos * multiplicator) + 'px';
    }.bind(this), 1000);
}

关于Javascript setInterval 不适用于此。对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42211072/

相关文章:

python - 在 Python 中创建类的开销 : Exact same code using class twice as slow as native DS?

Java:为什么不覆盖 "this( )"?

javascript - 如何将它绑定(bind)到 AngularIO 的 Observable::subscribe 函数?

javascript - 如何通过 Azure Cosmos DB 中的存储过程查询数据库

javascript - 使用 jquery cookie 的第三方 cookie

php - 这两种初始化 PHP 类的方法有什么区别?

javascript - 我可以在 jQuery 中的 "this"之后添加更多吗?

javascript - Handlebars 助手未获取变量值

javascript - 如何使用 JavaScript 的仅 float 学来计算时间差?

php - 类文件如何使用命名空间和使用包含在另一个文件 php 中?