先看代碼,首先創(chuàng)建了People的類抹沪,然后創(chuàng)建Student類繼承自People刻肄,最后new出來(lái)xiaochenchen的實(shí)例。
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}歲,學(xué)號(hào)${this.number},在學(xué)習(xí)${this.course}`)
}
}
const xiaochenchen = new Student('阿成', '12', '雞腿', '250', '高數(shù)')
xiaochenchen.eat() // 阿成eating 雞腿
xiaochenchen.study() // 阿成 今年12歲,學(xué)號(hào)250,在學(xué)習(xí)高數(shù)
其中融欧,實(shí)例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,從而形成了一條原型鏈董济。
原型圖如下:
補(bǔ)充
People.__proto__ == Function.prototype // true
Function.prototype.__proto__ == Object.prototype // true
Object.constructor.__proto__ == Function.prototype // true