先看代码,首先创建了People的类,然后创建Student类继承自People,最后new出来xiaochenchen的实例。
class People {
constructor(name, age, food) {
this.name = name
this.age = age
this.food = food
}
eat() {
console.log(`${this.name}eating ${this.food}`)
}
}
class Student extends People {
constructor(name, age, food, number, course) {
super(name, age, food)
this.number = number
this.course = course
}
study() {
console.log(`${this.name} 今年${this.age}岁,学号${this.number},在学习${this.course}`)
}
}
const xiaochenchen = new Student('阿成', '12', '鸡腿', '250', '高数')
xiaochenchen.eat() // 阿成eating 鸡腿
xiaochenchen.study() // 阿成 今年12岁,学号250,在学习高数
其中,实例xiaochenchen有 _ proto _ 属性,我们称之为隐式原型;类People和Student有prototype属性,我们称之为显式原型。
typeof xiaochenchen // 'Object'
typeof Student // 'funtcion'
typeof People // 'function'
xiaochenchen instanceof Student // true
xiaochenchen instanceof People // true
xiaochenchen instanceof Object // true
xiaochenchen.__proto__ // People {constructor: ƒ, study: ƒ}
Student.prototype // People {constructor: ƒ, study: ƒ}
xiaochenchen.__proto__ === Student.prototype // true
Student.prototype.__proto__ === People.prototype // true
People.prototype.__proto__ === Object.prototype // true
Object.prototype.__proto__ // null
由以上可以看出xiaochenchen._ proto _ 指向Student.prototype;
Student.prototype._ proto _ 又指向了People.prototype;
People.prototype._ proto _最终指向了Object.prototype;
而Object.prototype._proto _ 最终指向了null,从而形成了一条原型链。
原型图如下:
补充
People.__proto__ == Function.prototype // true
Function.prototype.__proto__ == Object.prototype // true
Object.constructor.__proto__ == Function.prototype // true