Skip to main content

寄生组合式继承例子2

//类
function Animal(name) {
console.log("父类构造函数----->", this);
this.name = name || "Animal";
this.sleep = function () {
console.log(this.name + "正在睡觉!");
};
this.getName = function () {
console.log(this.name);
};
}
Animal.prototype.eat = function (food) {
//原型方法
console.log(this.name + "正在吃:" + food);
};

//6.寄生组合继承
//6.寄生组合继承:核心:通过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性,避免的组合继承的缺点
function Cat_6(name) {
Animal.call(this);
this.name = name || "Tom";
}
(function () {
// 创建一个没有实例方法的类
var Super = function () {};
Super.prototype = Animal.prototype;
//将实例作为子类的原型
Cat_6.prototype = new Super();
})();

var cat_6 = new Cat_6();
console.log("F-1:", cat_6.name);
console.log("F-2:", cat_6.sleep());
console.log("F-3:", cat_6 instanceof Animal); // true
console.log("F-4:", cat_6 instanceof Cat_6); //true
// 感谢 @bluedrink 提醒,该实现没有修复constructor。
Cat_6.prototype.constructor = Cat_6; // 需要修复下构造函数