class Anamal {//抽象类
constructor(name, age) { //实例本身的属性
if (new.target == Anamal) {
throw new Error("抽象类不能直接实例化, 请用该类的子类创建对象");
}
this.name = name;
this.age = age;
}
yaoren() {
console.log("yaoren....");
}
}
class Dog extends Anamal {
constructor(name, age, weight) { //实例本身的属性
super(name, age);
this.weight = weight;
}
static eat = "狗粮" //静态属性和静态方法
static walk = function () {
console.log("我会跑");
};
print() { //prototype上的属性
console.log(`[name:${this.name};age:${this.age}]`);
}
color = "black"; //实例本身不需要传参的属性
set age(age) { //setter/getter方法, 实例.age时候该方法会自动找到该函数 该函数会额外创建一个_age属性, 来存该属性值. 其实我认为是一种浪费, 应该还有更好的方法才对
if (age < 0) {
age = 0;
} else if (age > 100) {
age = 100
}
this._age = age;
}
get age() {
return this._age;
}
}