引言----感謝大佬的講解
大佬鏈接
原型鏈示意圖
原型鏈問題中需要記住一句話:一切變量和函數都可以并且只能通過__proto__去找它所在原型鏈上的屬性與方法
原型鏈需要注意的點
看上圖可以發現
- 函數(構造函數)也可以通過__proto__去找到原型對象也就是Function.prototype
Function.__proto__ === Function.prototype
練習題
function Test(name, age){this.name = namethis.age = age
}
var obj = new Test('Jack', 26)Object.prototype.price = 2000Function.prototype.price = 300console.log(Test.price) // 300
console.log(obj.price) // 2000
原型鏈繼承的方式
function Person (name, age) {this.name = namethis.age = age
}// person的子類
function Student (name, age, score) {Person.call(this, name, age)this.score = score
}
// 1. 根據原型創建一個空對象
Student.prototype = Object.create(Person.prototype) // Object.create(Person.prototype)創建的對象是一個以Person.prototype為原型的對象
// 2. 修改Student的prototype的constructor
Student.prototype.constructor = Student // 繼承
// 3.更新tostring方法
Student.prototype[Symbol.toStringTag] = Student.namelet s1 = new Student('wangwu', 18, 100)
console.log('s1.__proto__', s1.__proto__)
console.log('s1.__proto__.__proto__', s1.__proto__.__proto__)
console.log('Person.prototype', Person.prototype)
console.log('Object.prototype.toString.call(s1)', Object.prototype.toString.call(s1));