js的继承
1.原型链继承
//父类
function Animal (name) {
this.name = name || 'Animal';
this.sleep = function(){
console.log(this.name + '正在睡觉!');
}
}
Animal.prototype.eat = function(food) {
// 原型方法
console.log(this.name + '正在吃:' + food);
};
//子类
function Cat(){
}
Cat.prototype.name = 'cat';
//继承 继承父类的构造函数里的方法和原型上的方法,实例新增的方法继承不到
Cat.prototype = new Animal();
console.log(cat instanceof Animal); //true
console.log(cat instanceof Cat); //true
2.构造函数继承
function Cat(name){
Animal.call(this);//继承了父类构造函数/实例的属性,没有继承父类原型的属性
this.name = name || 'Tom';
}
var cat = new Cat();
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true
3.组合继承
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
Cat.prototype = new Animal();
//弥补了方式2的缺陷,可以继承实例属性/方法,也可以继承原型属性/方法
var cat = new Cat();
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true