一些面向對象語言中支援多繼承,在JavaScript也能實作多繼承,但是有一些局限,因為在JavaScript中繼承是依賴原型prototype鍊實作的,隻有一條原型鍊,是以理論上是不能繼承多個父類的。但是JavaScript很靈活,通過一些技巧方法可以繼承多個對象的屬性來實作類似的多繼承。
單繼承
繼承單對象的extend方法:
//單繼承 屬性複制
var extend = function (target,source) {
//周遊源對象中的屬性
for(var property in source){
//将源對象中的屬性複制到目标對象中
target[property] = source[property];
}
//傳回目标對象
return target;
};
單繼承的測試代碼
//測試代碼
var book ={
name:'javascript',
alike:['css','html5','js']
}
var anotherBook = {
color :'blue'
}
extend(anotherBook,book);
console.log(anotherBook.name);//javascript
console.log(anotherBook.alike);//[ 'css', 'html5', 'js' ]
anotherBook.alike.push('ajax');
anotherBook.name = '設計模式';
console.log(anotherBook.name);//設計模式
console.log(anotherBook.alike);//[ 'css', 'html5', 'js', 'ajax' ]
console.log(book.name);//javascript
console.log(book.alike);//[ 'css', 'html5', 'js', 'ajax' ]
上面的方法可以實作對一個對象屬性的複制繼承,當傳遞多個對象時,即可實作多繼承。
多繼承
//多繼承 屬性複制
var mix = function () {
var i =1,//從第二個參數起為被繼承的對象
len =arguments.length,//擷取參數長度
target = arguments[0], //第一個對象為目标對象
arg;//緩存參數對象
for(;i<len;i++){
//緩存目前對象
arg = arguments[i];
//周遊被繼承對象中的屬性
for(var property in arg){
//将被繼承對象的屬性複制到目标對象中
target[property] = arg[property];
}
}
//傳回目标對象
return target;
};
mix方法的作用是将傳入的多個對象的屬性複制到源對象中,這樣即可實作對多個對象的屬性的繼承。另外當使用的時候需要傳入目标對象(第一個參數-需要繼承的對象)時,可以将它綁定到原生對象Object上,這樣所有的對象都可以擁有這個方法。這樣就可以在對象上直接調用。
Object.property.mix = function () {
var i=0,//從第一個參數起為被繼承的對象
len =arguments.length,//擷取參數長度
arg;//緩存參數對象
for(;i<len;i++){
//緩存目前對象
arg = arguments[i];
//周遊被繼承對象中的屬性
for(var property in arg){
this[property] = arg[property];
}
}
}