如何为 javascript class 属性创建方法?

How to create methods for javascript class properties?

我可能完全误解了 类 但这就是我想做的。

我有很多不同的颜色,每种颜色都有自己的一套色调。每种颜色由一组 R、G、B 组成。我希望能够创建新颜色,然后访问不同格式的属性,例如 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"));

这可行,但如果能够执行类似的操作来访问 css rgba 字符串会更主动。这可能吗?

const rgba = pink.light.rgba();

使用另一个 class 或对象,并将构造函数参数转换为该对象,而不是将字符串分配给 this.dark,等等

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());