drawing.draw is not a function

0

hla I am learning javascript and in this occasion I run into a problem that maybe is something very basic but as I am just learning to program I do not give with the error. In code that I will leave below an error occurs when I try to access the draw property, when I was researching the objects in javascript recommended that instead of our constructor create a function grow for each of the instances as in the following code

    function Animal (edad) {
  this.edad = edad;
  this.crecer = function () {
    this.edad = this.edad + 1;
    return this.edad;
  }
}

so if we create an array with 1000 instances of Animal 1000 different (and independent) functions will be created, something that in terms of efficiency is tremendously undesirable.

therefore I recommended writing in the following way

    function Animal (edad) {
  this.edad = edad;
}

Animal.prototype.crecer = function () {
  this.edad = this.edad + 1;
  return this.edad;
};

Now in my code (I will discuss below) I store each object in an array and when trying to interact with each one and using the draw method, I get the following error drawing.draw is not a function

I do not know if I'm failing if someone has the answer, they explain to me

my code

    let x, y, newX, newY, oldy, oldx;
let circlecontainer= [];


for(let i = 0; i < 30; i++){

    let red = Math.random() * 250;
    let green = Math.random() * 250;
    let blue = Math.random() * 250;
    x = Math.random() * innerWidth;
    y = Math.random() * innerHeight;
    var circle = new Circle (x,y,red,green,blue);
    circlecontainer.push(circle);

}

for (let i = 0; i < circlecontainer.length; i++) {

    let dibujo =circlecontainer[i].draw();

}

function Circle (x,y,red,green,blue){

    this.x = x;
    this.y = y;
    this.red = red;
    this.green = green;
    this.blue = blue;

}




Circle.prototype.draw = function(){

    c.beginPath()
    c.arc(this.x, this.y, 10, 0, Math.PI * 2, false);
    c.fillStyle = 'rgba(${this.red},${this.green},${this.blue}, 0.7)';
    c.fill();
};
    
asked by Carlos Puente 05.06.2018 в 20:02
source

1 answer

1

The problem is that you modify the prototype of Circle by adding the draw method after trying to use it.

You must execute the instruction in which you extend the prototype before using the method:

Circle.prototype.draw = function(){

    c.beginPath()
    c.arc(this.x, this.y, 10, 0, Math.PI * 2, false);
    c.fillStyle = 'rgba(${this.red},${this.green},${this.blue}, 0.7)';
    c.fill();
};

for(let i = 0; i < 30; i++){

    let red = Math.random() * 250;
    let green = Math.random() * 250;
....
    
answered by 05.06.2018 / 20:14
source