Search code examples
javascriptarraysfunctionp5.jsarrow-functions

Returning array from arrow function in JavaScript


I'm making a solar system generator in JavaScript in p5.js and I want to return an array of rgb values from an arrow function but It doesn't work. The star is white instead of yellow, orange or red.

class Star {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = random(50, 70);
    this.color = () => {
      let colorChoice = floor(random(6));
      switch(colorChoice) {
        case 0: case 1: case 2: case 3:
          return [255, 255, 0];
          break;
        case 4:
          return [255, 150, 0];
          break;
        case 5:
          return [255, 0, 0];
          break;
      }
    }
  }

  show() {
    noStroke();
    fill(this.color[0], this.color[1], this.color[2]);
    circle(this.x, this.y, this.size);
  }
}

Is there something wrong in the function itself or elsewhere?


Solution

  • this.color - is a function. Try update your show() method to

    let color = this.color();
    fill(color[0], color[1], color[2]);