1. 首先理解使用class实现继承
extends关键字可以继承父类的属性和方法,通过super这个方法调用,其实是原型来实现
js
class Parent {//父类
constructor(name) {
this.name = name;
}
drink(){
console.log('喝水')
}
}
class Student extends Parent{//extends 继承父类
constructor(name, age) {
super(name)
this.age = age;
}
intruduce(){
console.log(`${this.name}已经${this.age}岁了`)
}
}
const student = new Student('张三', 3);
console.log(student, 'student');
student.intruduce();
class Person extends Parent{
constructor(name, age) {
super(name)
// this.name = name;
this.age = age;
}
}
const person = new Person('李四', 6);
console.log(person, 'person');
person.drink();
2. 原型是什么?
先上代码
js
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
intruduce(){
console.log(`${this.name}已经${this.age}岁了`)
}
}
const student = new Student('张三', 3);
console.log(student, 'student');
student.intruduce();
a. student实例对象
ⅰ. 下图可以看出,student对象这个实例对象并没有包含intruduce方法

ⅱ. 我们把它展开后,其实是包含在__proto__中

ⅲ. __proto__则为student的隐式原型
所以当我们去找一个对象的属性和方法的时候,当前的对象上找不到的时候,它就会去它的隐式原型上找,如果隐式原型上有这个方法,它就会去访问这个方法,然后进行调用。
调用方式就是student.proto
b. Student类
ⅰ. Student上面有一个属性叫prototype,也可以打印出它的方法

ⅱ. 而student.__proto__也同样有这些方法,我们对比后发现它们是一摸一样的

c. 从这张图可以看出它们指向同一个对象,而prototype是Student这个类的显示原型

3. 原型链又是什么?
在上代码
js
class Person {//父类
constructor(name) {
this.name = name;
}
drink(){
console.log('喝水')
}
}
class Teacher extends Person{
constructor(name, age) {
super(name);
this.age = age;
}
intruduce(){
console.log(`${this.name}已经${this.age}岁了`)
}
}
const teacher = new Teacher('张三', 3);
console.log(teacher, 'teacher');
teacher.intruduce();
a. 实例对象teacher调用一个方法,首先会在自身开始找,找不到就通过__proto__隐式原型所指向的Teacher类的显示原型的prototype去找,找到后执行这个方法,如果还是找不到,又因为Teacher.prototype是一个对象,那么它也有一个__proto__属性,然后就会去找它所继承的父类Person的显示原型Person.prototype里面的方法,所以teacher通过这样一个链一层一层的找到目标的方法,这就是我们所说的原型链。


b. 检测查看属性和方法是否是自身所拥有的
js
teacher.hasOwnProperty("teacher")//false
teacher.hasOwnProperty("name")//true
那么hasOwnProperty这个属性是从哪儿来的呢?
对象的最终会指向那我们发现person这个父类其实是继承了objects这个类,也就是person.Prototype的隐式原型__proto__其实是指向Object.prototype这个原型,然后所有的对象最终都会指向object,最后object对象的原型最终会指向null。


4. instanceof 检查类型

原理:原型链
如果是在teacher的原型链的东西,都会返回true,而Array不存在原型链上所以返回false
