参考书籍:JavaScript设计模式
在聊多继承之前先看看单继承extend。extend是继承单对象属性,实现的是对单对象属性复制的一个过程。如:
//extend:继承单对象属性
var extend = function (target, source) {
//遍历源对象属性
for (var property in source) {
//将源对象的属性赋值到目标对象中
target[property] = source[property];
}
//返回目标对象
return target;
}
测试
var book = {
name: "javascript",
alike: ['css', 'html']
}
var anotherBook = {
color: "red"
}
extend(anotherBook, book);
console.log(JSON.stringify(anotherBook));//{"color":"red","name":"javascript","alike":["css","html"]}
anotherBook.alike.push("vue");
anotherBook.name = "react";
console.log(JSON.stringify(anotherBook));//{"color":"red","name":"react","alike":["css","html","vue"]}
console.log(JSON.stringify(book));//{"name":"javascript","alike":["css","html","vue"]}
可以发现extend只能对值类型的属性实现复制,也就是浅复制。对于引用类型的属性会遇到和类式继承一样的问题。在jQuery等一些框架中实现了深复制,就是将源对象中的引用类型再执行一遍extend方法。
多继承,基于值类型属性的多继承
Object.prototype.mix = function () {
//缓存参数对象
var arg;
//遍历被继承的对象
for (var i = 0, len = arguments.length; i < len; i++) {
//缓存当前参数对象,源对象,被继承对象
arg = arguments[i];
//遍历被继承对象中的属性
for (var property in arg) {
//将被继承对象的属性赋值到目标对象this中,
this[property] = arg[property];
}
}
}
测试
var book = {
name: "javascript",
alike: ['css', 'html']
};
var book1 = {
about: "book"
}
var anotherBook = {
color: "red"
}
anotherBook.mix(book, book1);
console.log(JSON.stringify(anotherBook));//{"color":"red","name":"javascript","alike":["css","html"],"about":"book"}
anotherBook.alike.push("vue");
anotherBook.name = "react";
console.log(JSON.stringify(anotherBook));//{"color":"red","name":"react","alike":["css","html","vue"],"about":"book"}
console.log(JSON.stringify(book));//{"name":"javascript","alike":["css","html","vue"]}