Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript类中使用实例方法_Javascript_Oop_Object_Inner Classes - Fatal编程技术网

如何在javascript类中使用实例方法

如何在javascript类中使用实例方法,javascript,oop,object,inner-classes,Javascript,Oop,Object,Inner Classes,我创建了一个类,在这个类中,我想根据rgb颜色值计算十六进制颜色值,这个值应该在给定的类中首先计算。我在一个函数中这样做没有问题,但我想检查一下我是否也能在一个类中这样做 我的动机是在最后计算HSL颜色值,并从中运行该类的几个实例,以显示随机创建的颜色的不同细微差别 基本上,我想知道如何在hex()实例方法中使用rgb()实例方法值 以下是codepen的代码: https://codepen.io/buzzer79/pen/LJVxmP/ 我也在这里复制它: class Colors {

我创建了一个类,在这个类中,我想根据rgb颜色值计算十六进制颜色值,这个值应该在给定的类中首先计算。我在一个函数中这样做没有问题,但我想检查一下我是否也能在一个类中这样做

我的动机是在最后计算HSL颜色值,并从中运行该类的几个实例,以显示随机创建的颜色的不同细微差别

基本上,我想知道如何在
hex()
实例方法中使用
rgb()
实例方法值

以下是codepen的代码:

https://codepen.io/buzzer79/pen/LJVxmP/
我也在这里复制它:

class Colors {
  constructor(R, G, B, H, E, X) {
    this.R = R;
    this.G = G;
    this.B = B;
    this.H = H;
    this.E = E;
    this.X = X;
  }

  rgb() {
    //calculate RGB
    this.R = Math.floor(Math.random() * 255);
    this.G = Math.floor(Math.random() * 255);
    this.B = Math.floor(Math.random() * 255);

    return this.R + "," + this.G + "," + this.B;
  }

  hex() {
    //calcuate hex
    this.H =
      this.R.toString(16).length < 2
        ? "0" + this.R.toString(16)
        : this.R.toString(16);
    this.E =
      this.G.toString(16).length < 2
        ? "0" + this.G.toString(16)
        : this.G.toString(16);
    this.X =
      this.B.toString(16).length < 2
        ? "0" + this.B.toString(16)
        : this.B.toString(16);
    // return this.H+''+this.E+''+this.X;
  }
}
类颜色{
构造函数(R、G、B、H、E、X){
这个。R=R;
这个.G=G;
这个.B=B;
这个,H=H;
这个。E=E;
这个.X=X;
}
rgb(){
//计算RGB
this.R=Math.floor(Math.random()*255);
this.G=Math.floor(Math.random()*255);
this.B=Math.floor(Math.random()*255);
返回this.R+“,“+this.G+”,“+this.B”;
}
十六进制(){
//计算十六进制
这个=
此.R.toString(16).长度<2
?“0”+此.R.toString(16)
:此.R.toString(16);
这个=
此.G.toString(16).长度<2
?“0”+此.G.toString(16)
:此.G.toString(16);
这个.X=
此.B.toString(16).长度<2
?“0”+此.B.toString(16)
:此.B.toString(16);
//返回这个.H+''+这个.E+''+这个.X;
}
}

您需要使用
this.
来访问实例属性。您的构造函数没有多大意义。另外,您不应该存储颜色值两次-存储颜色一次(以规范格式),并将其他颜色作为getter派生。“HEX”不是一种颜色格式。这是一种数字格式,用于(除其他外)RGB数字。