0
class Color {
constructor(red, green, blue) {
    this.red = red;
    this.green = green;
    this.blue = blue;
}

  generateColor(){
    // this.red, this.green, this.blue = this.randomColor() ???
    return (`Random Color : \n Red : ${this.red}\n Green : ${this.green}\n Blue : 
             ${this.blue}`)
  }

  randomColor() {
    return Math.floor(Math.random() * 256);
  }
}

How can i make this kind of multiple assignment without using arrays ?

2 Answers2

1

To assign three properties of your object with a single line of code use Object.assign() with this as first arg and an object literal as the second.

class Color {
constructor(red, green, blue) {
  this.red = red;
  this.green = green;
  this.blue = blue;
}

  generateColor(){
    // this.red, this.green, this.blue = this.randomColor() ???
    Object.assign(this, {red: this.randomColor(), green: this.randomColor(), blue: this.randomColor()});

    return (`Random Color : \n Red : ${this.red}\n Green : ${this.green}\n Blue : ${this.blue}`)
  }

  randomColor() {
    return Math.floor(Math.random() * 256);
  }
}

const colorObj = new Color('55','33','11');

console.log(colorObj.generateColor());
WillD
  • 5,170
  • 6
  • 27
  • 56
  • I think what he's asking about is the commented assignment in `generateColor`, not the assignments to `this.XXX` – Barmar Aug 23 '22 at 01:07
  • inside generateColor() i need to assign a new value to each variable and print it ("Look for the commented line"). BUT i learned something new ! thanks anyway :) – Matias Cabral Aug 23 '22 at 01:07
  • Ok, I have updated my answer using the same method but in the correct place. – WillD Aug 23 '22 at 01:09
  • You're using the same random value for all components of the color. I don't think he wants that. – Barmar Aug 23 '22 at 01:11
  • @WillD Oh NO :( i thought this may work, but Barmar is right i need different random values. – Matias Cabral Aug 23 '22 at 01:13
  • @MatiasCabral updated, they will now be three different random values. – WillD Aug 23 '22 at 01:14
  • @WillD i think this is the best approach, but it looks like javascript doesn't have that kind of assignment like the commented line. Thanks for your time ! :) – Matias Cabral Aug 23 '22 at 01:20
1

class Color {
constructor(red, green, blue) {
    this.red = red;
    this.green = green;
    this.blue = blue;
}

  generateColor(){
    [this.red, this.green, this.blue] = [this.randomColor(), this.randomColor(), this.randomColor()]
    return (`Random Color : \n Red : ${this.red}\n Green : ${this.green}\n Blue : ${this.blue}`)
  }

  randomColor() {
    return Math.floor(Math.random() * 256);
  }
}

const colorObj = new Color('1','1','1');

console.log(colorObj.generateColor());
Jeffrey Ram
  • 1,132
  • 1
  • 10
  • 16