<分区>
我在使用 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)?