从a类到b类理解原型链
一.一个Student类
class Student {constructor(name, age) {this.name = name;this.age = age;}learn() {console.log("学习");}}let a1=new Student('王德发',20)console.log(a1);
打印出来的结果:
二.extends继承
// 老师类class Teacher {constructor(name, age) {this.name = name;this.age = age; //工资}teach() {console.log("教书");}}// 学生类 继承 父类class Student extends Teacher {constructor(name, salary) {super(name);this.salary = salary; //工资}learn() {console.log("学习");}}// 创建一个学生的实例化对象var student1 = new Student("吕德华", 3000);// 打印这个实例化对象console.log(student1);
打印的结果:
三.访问的过程
__proto__作为存取器属性,在内部指向 [ [Prototype]],不过 [ [Prototype]]是不能在代码中直接访问的,只能通过__proto__访问
四.总结
所有的 JavaScript 对象都会从一个 prototype(原型对象)中继承属性和方法。
上述案例我们访问tach方法。
可以访问
为什么能访问?
这里可以理解为:
Student类继承了Teacher这个类,所以能够访问,但是以什么方式进行传递的呢?
1.首选查找自己类上有没有teach这个方法,没有。
2.查他的上上一级类,也就是继承的类Teacher这个类。
那么以什么方式进行查找的呢?
Student这个类上的prototype属性,也是一个对象,那么在他的基础上加上一层prototype(原型对象)
来实现方法的传递。