I have an ‘object’:
function Rock()
{
this.size = 30.0;
this.body;
this.isDead = false;
this.vertexPosBuffer;
this.vertexColBuffer;
}
which I give a function:
Rock.prototype.Tick = function()
{
this.body.ApplyForce(new b2Vec2(0, 10), this.body.GetPosition());
}
and then I make an array of rocks:
var rocks;
function NewRandomRock()
{
var newRock = new Rock;
var pos = new b2Vec2;
pos.x = Math.random()*(gl.viewportWidth+1);
pos.y = Math.random()*(gl.viewportHeight+1);
newRock.InitRand(pos);
rocks.push(newRock);
}
and then I call the Tick function:
function TickRocks()
{
for(var rock in rocks)
{
rock.Tick();
}
}
Now the problem, I get the following error:
Uncaught TypeError: Object 0 has no method ‘Tick’
Though the “InitRand(…)” methods, which I add to the Rock the same way, does work…
What am I doing wrong ?
Your problem is that using
for inis not made for iterating over arrays. It’s made to enumerate over object properties.You should use a normal for loop: