class类

136 阅读1分钟

class类返回的是一个对象

class定义的需要new 出来 形成一个实例  constructor就是初始化的数据

class Box{   
   constructor(color){
      this.color=color,
      this.type="class"
    }
}

const newBox=new Box("myIsColor")
console.log("box",newBox) 

结果为:

直接在construtor函数外,会直接加到初始化对象里面 

class Box{
    one="one"
   constructor(color){
     this.color=color,
     this.type="class"
   }
}

const newBox=new Box("myIsColor")
console.log("BOX",newBox)

class 里面声明函数

class Box{
        one="one"
   construtor(color){
     this.color=color,
     this.type="class"
   }

   hello(){    //class里面定义函数是这样的形式  
       return hello  这样会报错
       return "hello"  不会报错
   }
}

const newBox=new Box("myIsColor");
console.log("box",newBox.hello())   // 结果为:hello

静态属性 static声明  静态方法指的是类 而不是实例

class Box{
        one="one"
   construtor(color){
      this.color=color,
      this.type="class",
      this.sta=Box.classSt
   }

  static classSt="classSt"
}

const newBox=new Box("myIsColor")
console.log("Box",newBox)

得到的结果为:

class Box{
   one="one",
  constructor(color){
    this.color=color,
    this.type="class",
    this.sta=Box.calssSt,
    this.fn=Box.fn()
  }

    static classSt="classSt"

    static fn(){
      return "fn"
    }
}

const newBox=new Box("myIsColor")
console.log("box",newBox)

结果为: