通过class进一步理解原型和原型链
class Persion{
constructor(name,age){
this.name = name
this.age = age
}
}
let xiaoming = new Persion("xiaoming",20)
console.log(xiaoming)
打印结果如下:
我们再来看上面用class原型生成实例的打印结果,Persion实例有隐式属性__proto__,指向了它的原型Persion的prototype,Persion同时也是一个对象,是由Object构造的,最终原型链又指向了Object。
什么是原型:其实就是构造函数里面有一个prototype属性,而prototype属性里面有constructor,那么constructor的作用是什么呢,它其实指向的是构造函数本身。
用class我们可以很方便的实现继承,使用extends关键字
class Persion{
constructor(name,age){
this.name = name
this.age = age
}
}
class Student extends Persion{
constructor(name,age){
super(name,age)
}
}
let xiaoming = new Student("xiaoming",20);
console.log(xiaoming)
我们可以看到,使用extends继承也是可以通过原型链逐级查找到Object对象的。
这时候如果我们在Persion上添加一个方法say,尝试打印继承了Persion的Student原型生成的实例xiaoming的say()方法。
class Persion{
constructor(name,age){
this.name = name
this.age = age
}
say(){
console.log("hi")
}
}
class Student extends Persion{
constructor(name,age){
super(name,age)
}
}
let xiaoming = new Student("xiaoming",20);
console.log(xiaoming)
xiaoming.say();//hi
在控制台看出,xiaoming.say()成功执行了,这就印证了原型链逐级查找的特点,首先xiaoming在自己内部查找say方法,但是没有查到,这时候自动向下继续查找say方法,这时候查到了Persion原型上有这个方法,那么就相当于xiaoming有了say方法
总结:1 实例的__proto__===原型的prototype
2 原型链具有逐级查找特性:先自身查找,如果没有那就去自身原型的prototype属性上找,如果prototype属性上没有,那就用._proto_上找,一直找到最顶层的Object上找,直返返回null为止。
3 xiaoming能调到say方法,persion和people都能调到say方法,这时候可以用xiaoming.hasOwnProperty(‘say’)判断,返回false
ps:补充一个知识点,用 a instanceof b 可以判断a是不是b生成的实例,或者叫b是不是a的原型,只要b在a所处的上游原型链上,就返回true
举个🌰:xiaoming instanceof Student //true
xiaoming instanceof People //true
xiaoming instanceof Object //true
xiaoming instanceof Array //false