// 继承
// 定义一个动物类
function Animal (name) {
// 属性
this.name = name || 'Animal';
// 实例方法
this.sleep = function(){
console.log(this.name + '正在睡觉!');
}
}
// 原型方法
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃:' + food);
};
//方法1 原型链继承
// function Cat(){
// }
// Cat.prototype = new Animal();
// Cat.prototype.name = 'cat';
// var cat = new Cat();
// console.log(cat.name);
// console.log(cat.eat('fish'));
// 方法2 构造继承
// function Cat(name){
// Animal.call(this);
// this.name = name || 'Tom';
// }
// var cat = new Cat();
// console.log(cat.name)
// console.log(cat.sleep());
//3 实例继承 --为父类实例添加新特性,作为子类实例返回
// function Cat(name){
// var instance = new Animal();
// instance.name = name || 'Tom';
// return instance;
// }
// 4 4、拷贝继承
// function Cat(name){
// var animal = new Animal();
// for(var p in animal){
// Cat.prototype[p] = animal[p];
// }
// Cat.prototype.name = name || 'Tom';
// }
// 混合继承
// function Cat(name){
// Animal.call(this);
// this.name = name || 'Tom';
// }
// Cat.prototype = new Animal();
// 既是子类的实例,也是父类的实例。不存在引用共享的问题,可以传参;
// 原型链继承-》缺点
//1,:创建子类实例时,无法向父类构造函数传参
//2 ,无法实现多继承;
// 构造继承 缺点:
//1.实例并不是父类的实例,只是子类的实例;
//2.只能继承父类的实例属性和方法,不能继承原型属性/方法
//3.无法实现函数复用,每个子类都有父类实例函数的副本,影响性能
//!!6、寄生组合继承
//通过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性,避免的组合继承的缺点
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
(function(){
// 创建一个没有实例方法的类
var Super = function(){};
Super.prototype = Animal.prototype;
//将实例作为子类的原型
Cat.prototype = new Super();
})();
// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep())