0

I'm just playing around with JavaScript by having a button create a small square which moves downwards indefinitely. However, I ran into a small problem of which I don't understand why.

The code is like so:

var parentContainer = document.querySelector('.container'),
    inc = 5;

function Square()
{
    this.pos = 0;
    var thisSquare = null;

    this.create = function()
    {
        var newSquare = document.createElement('div');
        newSquare.className = 'square';
        newSquare.style.top = this.pos + "px";

        thisSquare = parentContainer.appendChild(newSquare);
    }

    this.getSquare = function()
    {
        return thisSquare;
    }

    this.update = function()
    {
        this.pos += inc;
        this.getSquare().style.top = this.pos + "px"; // Ln 26
    }
}


var square = new Square();
square.create();
setInterval(square.update, 100);

console.log(square.getSquare()); // Ln 35

The lines marked are where the confusion occurs.

Line 26 and line 35 do in essence the same, calling the getSquare() method, however Line 26 fails where Line 35 succeeds.

Line 35 gives me a Node, which is what I want. However, Line 26 gives the error:

Uncaught TypeError: undefined is not a function

Before I used var thisSquare = null;, I used this.square. Applying the same logic, I got the error:

Uncaught TypeError: Cannot set property 'top' of undefined

Could someone explain to me why I'm getting this error? For I am lost.

MisterBla
  • 2,355
  • 1
  • 18
  • 29
  • 2
    `setInterval(square.update.bind(square), 100)` – elclanrs Sep 08 '14 at 21:58
  • 2
    `setInterval` is calling the callback as a function, i.e. with the `this` value being the global scope. You'll need to pass a callback that calls it *as a method*. – Bergi Sep 08 '14 at 21:58

1 Answers1

1

this keyword will be undefined inside your nested function (i.e. setInterval function), so you need considering like below to make this to refer your object:

Use bind method:

var square = new Square();
square.create();
setInterval(square.update.bind(square), 100);
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231