简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM