class 和 继承
子类通过extends 和super 继承父类中的属性和方法
Student和Tearcher可以继承people中的name和eat()方法
<script>
//父类
class People {
constructor(name) {
this.name = name
}
eat() {
// console.log(this.name + 'eat something')
console.log(` ${this.name} eat something`)
}
}
// 子类
class Student extends People{
constructor(name, number){
super(name);
this.number = number
}
sayHi(){
console.log(`姓名 ${this.name} , 学号 ${this.number}`)
}
}
//子类
class Teacher extends People{
constructor(name,major){
super(name);
this.major = major;
}
teach (){
console.log(`姓名 ${this.name} 教 ${this.major}`)
}
}
const xialuo = new Student('夏洛','100');
console.log(xialuo.name)
console.log(xialuo.number)
xialuo.sayHi()
xialuo.eat()
const laowang = new Teacher('王老师','语文');
console.log(laowang.name)
console.log(laowang.major)
laowang.teach()
laowang.eat();
console.log('xialuo.__proto__ 隐式原型 --->'+ JSON.stringify( xialuo.__proto__));
console.log('Student.prototype 显式原型 --->'+ JSON.stringify(Student.prototype));
Student.prototype === xialuo.__proto__ // true
</script>
为了好理解可以画图

1.png
xlaluo的 __proto__和Student的prototype指向同一个sayHi();
原型关系
1.每个class都有一个显式的prototyp
2.每个实例都有一个隐式 __proto__
3.实例的 __proto__ 指向对应的class的prototyp
执行规则
获取实例属性
xialuo.name或执行方法sayHi()时先在自身属性和方法中寻找
3.找不到则自动到隐式原型中寻找。如 xialuo中的name和number是在自身中寻找。sayHi()是在 Student中寻找