1

I might be totally getting the wrong idea of classes but this is what I want to do.

I have a load of different colours each with their own set of shades. Each colour is made up of an array of R,G,B. I want to be able to create new colours and then access different formatted properties, like css rgba.

class Color {
  constructor(dark, light, white, id) {
    this.dark = dark;
    this.light = light;
    this.white = white;
  }
  rgba(shade, opacity = 1) {
    return `rgba(${this[shade].join(", ")}, ${opacity})`;
  }
}

const pink = new Color(
  [226, 155, 166], [240, 214, 219], [250, 245, 246]
);

//get rgba css string for a shade
console.log(pink.rgba("light"));

This works but it would be more initiative to be able to do something like this to access the css rgba string. Is this possible?

const rgba = pink.light.rgba();
3
  • 1
    You should define a new class, and make the properties instances of this class. Commented Nov 3, 2021 at 15:07
  • Yes, it is possible, I recommend to you read developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… and some javascript OOP article, I tried to help you but I dont understand your question at all Commented Nov 3, 2021 at 15:16
  • Your really should have a Color class that represents a particular, single color, and a Tone class that comes with three different shades of color. Commented Nov 3, 2021 at 15:45

1 Answer 1

3

Use another class or object, and transform the constructor arguments into that instead of assigning strings to this.dark, etc.

const makeShade = arr => ({
  rgba: (opacity = 1) => `rgba(${arr.join(", ")}, ${opacity})`
});

class Color {
  constructor(dark, light, white, id) {
    this.dark = makeShade(dark);
    this.light = makeShade(light);
    this.white = makeShade(white);
  }
}

const pink = new Color(
  [226, 155, 166], [240, 214, 219], [250, 245, 246]
);

//get rgba css string for a shade
console.log(pink.light.rgba());

Sign up to request clarification or add additional context in comments.

3 Comments

This so almost what I am looking for! Except I still want to preserve my array for future use. So maybe I can do pink.light.rgba() or pink.light.hsl() or just pink.light for the original.
A string cannot have properties. If you want to be able to do pink.light.rgba (as if .light was an object), there isn't any real way to have pink.light reference a string (a primitive). You'll need another property, eg makeShade = arr => ({ arr, rgba: (... and then reference the arr property
Yeah I think I get that, I will just have pink.light.rgba and pink.light.values etc... thank you very much :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.