Travis Michael Heller
Travis Michael Heller

Reputation: 1248

function is defined when out of loop but not when placed inside a loop?

I am trying to run a function within a loop but when I run it I get a robot.rn is not a function. when I run the function outside of the loop I have no problem and everything works as expected. I am sure it is something obvious hopefully and I have just been staring at my code too long. Any help would be greatly appreciated, thanks.

The basic idea i am trying to accomplish is drawing the coins in random positions 30 times(robot.maxCoins = 30);

when i run my code like this (outside of loop) it works

Robot.prototype.rn = function(){
    robot.rn = {
        rnX: robot.rnX = Math.floor(Math.random()*900)-20,
        rnY: robot.rnY = Math.floor(Math.random()*400)-20
    };
    return robot.rn;
};

Robot.prototype.drawCoins = function(){
    robot.rn();
    console.log(robot.rnX);
    ctx.beginPath();
    ctx.arc(robot.rnX,robot.rnY,robot.coinD,0,2*Math.PI);
    ctx.fillStyle = "yellow";
    ctx.fill();
    ctx.stroke();
};

Here is code with function in the loop (return: robot.rn is not a function)

Robot.prototype.rn = function(){
  robot.rn = {
    rnX: robot.rnX = Math.floor(Math.random()*900)-20,
    rnY: robot.rnY = Math.floor(Math.random()*400)-20
  };
  return robot.rn;
};

Robot.prototype.drawCoins = function(){
  for(var i = 0; i<robot.maxCoins; i++){
    robot.rn();
    console.log(robot.rnX);
    ctx.beginPath();
    ctx.arc(robot.rnX,robot.rnY,robot.coinD,0,2*Math.PI);
    ctx.fillStyle = "yellow";
    ctx.fill();
    ctx.stroke();
  }

};

Upvotes: 0

Views: 33

Answers (2)

Chet
Chet

Reputation: 3729

The first call to robot.rn replaces the function with an object. The second call in the loop tries to use that object as a function.

Just return you object from rn, don't assign it.

Upvotes: 0

mic4ael
mic4ael

Reputation: 8290

You are overwriting robot.rn

robot.rn = {
    rnX: robot.rnX = Math.floor(Math.random()*900)-20,
    rnY: robot.rnY = Math.floor(Math.random()*400)-20
};
return robot.rn;

It doesn't fail when you use it without a loop because you are not trying to call the rn function anymore.

Upvotes: 1

Related Questions