面向?qū)ο?四)
繼承
4. 多繼承——老師不止一位
- 首先表谊,JavaScript實(shí)現(xiàn)多繼承是有一些局限性的酿矢,因?yàn)镴avaScript中繼承時(shí)依賴于prototype鏈實(shí)現(xiàn)的秸滴,只有一條原型鏈逆济,所以理論上不能繼承多個父類的
- 通過一些技巧和方法可以繼承多個對象的屬性來實(shí)現(xiàn)類似的多繼承
// 繼承單對象屬性的方法extend方法
// 單繼承屬性復(fù)制
let extend = (target, source)=> {
// 遍歷元對象中的屬性
for(let property in target) {
// 將源對象中的屬性復(fù)制到目標(biāo)對象中
target[property] = source[property]
}
// 返回目標(biāo)對象
return target
}
測試代碼
let book = {
name: 'JavaScript 設(shè)計(jì)模式',
alike: ['css', 'html', 'JavaScript']
}
let anotherBook = {
color: 'blue'
}
extend(anotherBook, book)
console.log(anotherBook.name) // 'JavaScript 設(shè)計(jì)模式'
console.log(anotherBook.alike) // ['css', 'html', 'JavaScript']
anotherBook.alike.push('ajax')
anotherBook.name = '設(shè)計(jì)模式'
console.log(anotherBook.name) // 設(shè)計(jì)模式
console.log(anotherBook.alike) // ['css', 'html', 'JavaScript', 'ajax']
console.log(book.name) // JavaScript 設(shè)計(jì)模式
console.log(book.alike) // ['css', 'html', 'JavaScript', 'ajax']
傳遞多對象進(jìn)行繼承
// 多繼承 屬性復(fù)制
const mix= () =>{
let i = 1; // 從第二個參數(shù)起為被繼承的對象
let len = arguments.length // 獲取參數(shù)的長度
let target = arguments[0] // 第一個參數(shù)為目標(biāo)對象
let arg // 緩存參數(shù)對象
// 遍歷被繼承的對象
for(;i<len;i++){
// 緩存當(dāng)前對象
arg = arguments[i]
// 遍歷被繼承對象中的屬性
for(let property in arg){
// 將被繼承的對象的屬性復(fù)制到目標(biāo)對象中
target['property'] = arg['property']
}
}
// 返回目標(biāo)對象
return target
}
- 這個函數(shù)有個缺點(diǎn)爆土,需要傳入目標(biāo)對象(第一個參數(shù))
- 如果將它綁定到原生對象Object上的話搁嗓,所有對象都可以擁有這個方法 如下
Object.prototype.mix =()=> {
let i = 0 // 從第一個參數(shù)起為被繼承的對象
let len = arguments.length // 獲取參數(shù)的長度
let arg // 緩存參數(shù)對象
for(; i<len; i++) {
// 緩存當(dāng)前對象
arg = arguments[i]
// 遍歷被繼承對象的屬性
for(let property in arg) {
// 將被繼承對象中的屬性復(fù)制到目標(biāo)對象中
this[property] = arg[property]
}
}
}
測試代碼
let book1 = {
name: 'JavaScript 設(shè)計(jì)模式',
alike: ['css', 'html', 'js']
}
let book2 = {
color: 'blue'
}
let otherBook = {}
otherBook.mix(book1, book2)
console.log(otherBook) // Object { name:'JavaScript 設(shè)計(jì)模式', alike: Array(3), color: 'blue', mix: function }
明天繼續(xù)多態(tài)贬丛,還可能總結(jié)得到一設(shè)計(jì)模式了