0

So, i have the following code:

this.balls = [];

function setup() {
  createCanvas(800, 800);
  noStroke();
  balls.push(new Ball(width / 2, height / 2, 20))

}

function draw() {
  for (var ball in this.balls) {
    ball.drawCircle();
  }
}

this.Ball = function(x, y, r) {
  console.log("Ball created");
  this.x = x;
  this.y = y;
  this.r = r;

  this.drawCircle = function (){
    ellipse(x, y, r);
  }

}

The problem is that i get the following error:

Uncaught TypeError: ball.drawCircle is not a function
    at draw (sketch.js:12)
    at e.d.redraw (p5.min.js:6)
    at e.<anonymous> (p5.min.js:4)
    at e.<anonymous> (p5.min.js:4)
    at new e (p5.min.js:5)
    at e (p5.min.js:4)

So it should call the drawcircle funtion for every ball in the balls array, however it says that drawCircle is not a function. The problem is that I just don't understand why. I have tried using var drawCircle instead of this.drawCirle, I also tried using funcion drawCircle.

Kind regards.

p.s. this code uses p5.js, the Ball created log is executed

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Naugrim00
  • 61
  • 5
  • draw() is a function added by p5js, it gets called every frame – Naugrim00 May 31 '18 at 15:44
  • 1
    in the loop : `for (var ball in this.balls)`, `ball` is an integer ( the index ), try `for (var ball of this.balls) `, or keep the `in` and replace `ball.drawCircle();` with `this.balls[ball].drawCircle();` – Taki May 31 '18 at 15:44
  • 2
    This has nothing todo with scope or context, its a syntax error `for..in` instead of `for..of` – Jonas Wilms May 31 '18 at 15:55

1 Answers1

0

Try using a class so you don't have issues with this context:

function Ball(x, y, r) {
  console.log("Ball created");
  this.x = x;
  this.y = y;
  this.r = r;
}

Ball.prototype.drawCircle = function() {
  ellipse(x, y, r);
};

Or in ES6:

class Ball {
  constructor(x, y, r) {
    console.log("Ball created");
    this.x = x;
    this.y = y;
    this.r = r;
  }
  drawCircle() {
    ellipse(x, y, r);
  }
}
bc1105
  • 1,270
  • 8
  • 8
  • 1
    Doesn't this (apart from the ES6 part) functionally do the same thing? It feels like this would have the same issues. Happy to be corrected. I didn't downvote by the way. – Lewis May 31 '18 at 15:48
  • With the first option i still got the error, but the second one totally worked! thanks! (i cant accept an answer yet) – Naugrim00 May 31 '18 at 15:49
  • Yes, both do the same thing. Its just syntax. – bc1105 May 31 '18 at 15:50