代码
创建一个People类和Student类和一个Teacher类。
/* 创建一个People类 */
class People{
constructor(name){
this.name = name
}
eat(){
concole.log(this.name + 'eat something')
}
}
/* 创建一个继承People的Student类 */
class Student{
constructor(name,number){
super(name) //继承父类的name属性
this.number = number
}
sayHi(){
console.log(`${name}的学号是${number}`)
}
}
/* 创建一个Teacher类 */
class Teacher{
constructor(name,age){
super(name)
this.age = age
}
howOld(){
console.log(`${name}${age}岁`)
}
}
/* 实例化一个Student */
let xialuo = new Student("夏洛",100)
隐式原型和显式原型
根据以上的代码
xialuo.__proto__ //隐式原型
Student.prototype //显式原型
xialuo.__proto__ === Student.prototype //true
表明实例的隐式原型指向对应的class的显式原型
基于原型的执行规则
获取属性xialuo.name或执行方法xialuo.sayHi()时,先在自身属性和方法寻找。
如果找不到则自动去__proto__中查找
原型链
流程
xialuo.name 可直接在自身找到,不用往上找
xialuo.sayHi() 在自身无法找到,则通过自身__proto__的指向找到Student.prototype 的sayHi()
xialuo.eat() 在自身无法找到,则通过自身__proto__的指向找到Student.prototype。
然而Student.prototype中也没有eat(),则通过Student.__proto__的指向找到People.prototype 的eat()
xialuo.hasOwnPrototy()一次往上找,直到Object.prototype
注意Object的__proto__永远指向null