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.