3-29 寄生组合式继承
S继承的原理、方式和应用: https://www.cnblogs.com/yunshangwuyou/p/11968539.html
//寄生组合式继承(寄生式+原型:通过借用函数来继承属性,通过原型链的混成形式来继承方法)
function inheritObject(o) {
//声明一个过渡函数对象
function F() {}
//过渡对象的原型继承父对象
F.prototype = o;
//返回过渡对象的一个实例,该实例的原型继承了父对象
return new F();
}
function inheritPrototype(Child, Parent) {
//复制一份父类的原型副本保存在变量中
var p = inheritObject(Parent.prototype);
//修正因为重写子类的原型导致子类的constructor属性被修改
p.constructor = Child;
//设置子类的原型
Child.prototype = p;
}
//定义父类
function Parent(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
//定义父类的原型方法
Parent.prototype.getName = function() {
console.log(this.name);
}
function Child(name, time) {
//构造函数式继承
Parent.call(this, name);
this.time = time;
}
//寄生式继承父类原型
inheritPrototype(Child, Parent);
//子类新增原型方法
Child.prototype.getTime = function() {
console.log(this.time);
};
//创建两个测试方法
var test1 = new Child("js book", "2018-01-02");
var test2 = new Child("css book", "2018-01-03");
test1.colors.push("black")
test2.getName() //css book
test2.getTime() //2018-01-03
console.dir("-----------------test1--------------------")
console.dir(test1)
console.log(test1.colors); //["red", "blue", "green", "black"]
console.dir("-----------------test2--------------------")
console.dir(test2)
console.log(test2.colors); // ["red", "blue", "green"]