JS 的幾種繼承模式
1 原型鏈模式
function FatherType() {
this.colors = ['red', 'green', 'blue']
}
function SonType() { }
// 繼承
SonType.prototype = new FatherType()
let son = new SonType()
son.colors.push('black')
console.log(son.colors); // ["red", "green", "blue", "black"]
let son1 = new SonType()
console.log(son1.colors); // ["red", "green", "blue", "black"]
問題:
- 原型中包含的參考值會在所有實體間共享,
- 子型別在實體化時不能給父型別的建構式傳參,我們無法在不影響所有物件實體的情況下把引數傳進父類的建構式,
2 盜用建構式模式
基本思路:在子類的建構式中呼叫父類的建構式,
function FatherType(name) {
this.colors = ['red', 'green', 'blue']
this.name = name
}
function SonType(name) {
// 繼承
FatherType.call(this, name)
this.age = 12
}
let son = new SonType('li')
son.colors.push('black')
console.log(son.colors); // ["red", "green", "blue", "black"]
let son1 = new SonType('zhang')
console.log(son1.colors); // ["red", "green", "blue"]
console.log(son.name, son.age); // li 12
console.log(son1.name, son1.age); // zhang 12
優點:可以在子類建構式中向父類建構式傳參,
問題:
- 必須在建構式中定義方法,因此函式不能重用,
- 子類不能訪問父類原型上的方法,
3 組合繼承
組合繼承(經典繼承)綜合了原型鏈和盜用建構式,
基本思路:使用原型鏈繼承原型上的屬性和方法,通過盜用建構式繼承實體屬性,
function FatherType(name) {
this.colors = ['red', 'green', 'blue']
this.name = name
}
FatherType.prototype.say = function () {
console.log(this.name);
}
function SonType(name, age) {
// 繼承屬性
FatherType.call(this, name)
this.age = age
}
// 繼承方法
SonType.prototype = new FatherType()
SonType.prototype.sayAge = function () {
console.log(this.age);
}
let son = new SonType('li', 12)
son.colors.push('black')
console.log(son.colors); // ["red", "green", "blue", "black"]
son.say() // li
son.sayAge() // 12
let son1 = new SonType('zhang', 23)
console.log(son1.colors); // ["red", "green", "blue"]
son1.say() // zhang
son1.sayAge() // 23
4 寄生式組合繼承
組合繼承存在效率問題:父類建構式始侄訓被呼叫兩次,一次是在創建子類原型時呼叫,一次是在子類建構式中呼叫,
基本思路:不通過呼叫父類建構式給子類原型賦值,而是取的父類原型的一個副本,
function object(o) {
function F() { }
F.prototype = o
return new F()
}
// 寄生式組合繼承的核心邏輯
function inheritPrototype(sonType, FatherType) {
let prototype = object(FatherType.prototype) // 創建物件
prototype.constructor = sonType // 增強物件
sonType.prototype = prototype // 賦值物件
}
function Father(name) {
this.colors = ['red', 'green', 'blue']
this.name = name
}
Father.prototype.sayName = function () {
console.log(this.name);
}
function Son(name, age) {
Father.call(this, name)
this.age = age
}
inheritPrototype(Son, Father)
Son.prototype.sayAge = function () {
console.log(this.age);
}

寄生式組合繼承可以算是參考型別繼承的最佳模式,
參考文獻
[1] (美) 馬特·弗里斯比(Matt Frisbie)著. 李松峰譯. JavaScript高級程式設計: 第4版[M]. 人民郵電出版社, 2020.9
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/292743.html
標籤:其他
