Javascript setInterval does not work with this. objects

advertisements

This question already has an answer here:

  • How does the “this” keyword work? 18 answers
  • Javascript setInterval and `this` solution 8 answers

I'm having a problem with the setInterval() Method in Javascript. My main class:

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

And I have following constructor function.

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';
    }
}

Well that works fine by now, just moving every keyUp event 10px up. But I would like to call this.moveUp() every 1000 miliseconds automatically after the keyUp event. But when I try this:

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

I get an error that 'this' is null.

How can I fix it (Preferably without jQuery)?


You need to bind the setInterval to the same target as your class.

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