class继承主要还是会用到原型链的知识。
<script>
class Person {
constructor(name){
this.name = name
}
say(){
console.log("say hi")
}
}
class Student extends Person{
constructor(name, age){
super(name)
this.age = age
}
introduce(){
console.log(`我是${this.name}我今年${this.age}岁`);
}
}
class Teacher extends Person{
constructor(name, subject){
super(name)
this.subject = subject
}
introduce(){
console.log(`我是${this.name}我教${this.subject}`);
}
}
const student = new Student("Bob", 18)
console.log(student.name);
console.log(student);
student.introduce()
student.say()
console.log('-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_');
const teacher = new Teacher("Allen", "Math")
console.log(teacher.name);
console.log(teacher)
teacher.introduce()
teacher.say()
</script>
在Person类中定义了会用到的公共方法和属性,student和teacher类继承,其实例对象也会间接继承。
尤其要记得使用到super(【属性名】)来继承父类 ,否则会报错如下:
补上原型链的记忆图
实例对象的_proto_属性指向构造函数的prototype属性
实例对象的隐式原型指向构造函数的显式原型