目录

ES6ES6中的类

【ES6】ES6中的类

基础定义和使用

class Animal {
  constructor(name, species, age) {
    this.name = name
    this.species = species
    this.age == age
  }
}

let dog = new Animal("Spot", "Dog", 4)

私有变量

变量名前带#即可。

Getter 和Setter方法

继承

// 父类
class Point{
    constructor(x,y){
        this.x = x;
        this.y = y;
    }

    toString(){
        return this.x + ',' + this.y;
    }
}
// 子类
class ColorPoint extends Point{
    constructor(x,y,color){
        super(x,y); // 调用父类的构造函数
        this.color = color;
    }

    toString(){
        return this.color + ' ' + super.toString(); // 调用父类的toString()
    }
}

上面代码表示的类图关系如下:

https://i-blog.csdnimg.cn/direct/e58c630f6cc44d3f92b5373ad6e9762d.png

let cp = new ColorPoint(100,100,"red"); // 创建实例

console.log(cp); // 控制台输出

https://i-blog.csdnimg.cn/img_convert/7b14c8c535db10ae75c7c15216fb2eff.png#pic_center

重写

静态方法和静态属性