js inheritance
extends inheritance
class Person {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
show() {
console.log(`I'm a person. `);
}
say() {
console.log(`Hi, I'm a ${
this.name}. `);
}
}
// extends继承
class Teacher extends Person {
constructor(name, age, gender, subject) {
super(name, age, gender); //调用 父对象/父类 的构造函数(还可以调用父类方法: super.say() )
this.subject = subject;
}
// 重写
show() {
console.log(`I'm a Teacher. `);
}
// 添加新方法
teach() {
console.log(`I teach ${
this.subject}. `);
}
}
console.log("Person类--------------------------------------------------");
var per = new Person("李白", 55, "男");
per.show();
per.say();
console.log(
"Teacher类--------------------------------------------------"
);
var tea = new Teacher("李清照", "17", "女", "古诗词");
tea.show();
tea.say(); // 继承的方法
tea.teach();
parasitic compositional inheritance
- Use the constructor pattern to implement the constructor function and add methods to the prototype
父类.call()/aplly()
Parameter passing in subclass constructor pattern- Use the prototype of the parent class as a template to create an object and assign it to the prototype of the subclass
- Constructor on subclass prototype equals subclass constructor pattern function
- Write method on subclass prototype
Features:
- call the superclass constructor only once
- Child can pass parameters to Parent
- Parent class methods can be reused
- Reference attributes of the parent class will not be shared
Parasitic compositional inheritance can be regarded as the best mode of reference type inheritance