【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()
}
}
上面代码表示的类图关系如下:
let cp = new ColorPoint(100,100,"red"); // 创建实例
console.log(cp); // 控制台输出