Javascript setInterval 不适用于此。对象

Javascript setInterval doesn't work with this. objects

我在使用 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 事件向上移动 10px。 但我想在 keyUp 事件后每 1000 毫秒自动调用 this.moveUp() 一次。 但是当我尝试这个时:

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

我收到一条错误消息,提示 'this' 为空。

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

目标是setInterval

里面的Window对象

您要么需要捕获词法范围并使用它,要么使用 bind 将对象引用硬绑定到 setInterval 范围内的处理程序。

词法作用域的使用

this.moveUp = function() {
  // capturing the lexical scope
  var self = this;
  setInterval(function() {
    self.yPos--;
    self.domObj.style.top = (self.yPos * multiplicator) + 'px';
  }, 1000);
}

使用绑定

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

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

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