一段时间不用class就忘了咋使用了呜,记一下
原型继承写法:
function Father(name, age) {
this.name = name;
this.age = age;
}
Father.prototype = {
constructor: Father,
sing(song) {
console.log(this.name + "已经" + this.age + "了,爱唱" + song);
},
};
function Son(name, age, color) {
Father.call(this, name, age);
this.color = color;
}
Son.prototype = new Father();
Son.prototype.constructor = Son;
const f = new Father("John", 34);
f.sing("小星星");
const s = new Son("Eve", 12, "pink");
s.sing("孤勇者");
类继承写法:
class Father {
constructor(name, age) {
this.name = name;
this.age = age;
}
sing(song) {
console.log(this.name + "已经" + this.age + "了,爱唱" + song);
}
}
class Son extends Father {
constructor(name, age, color) {
super(name, age);
this.color = color;
}
sing(song) {
super.sing(song);
}
}
const f = new Father("John", 34);
f.sing("小星星");
const s = new Son("Eve", 12, "pink");
s.sing("孤勇者");
结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/83b1bbf96e48b70b6a326100f581346e.png)