js类的继承
//定义一个动物类
function Animal(name){
this.name = name || 'Animal';
//实例方法
this.sleep = function(){
console.log(this.name+'正在睡觉!');
}
//原型方法
Animal.prototype.eat = function(food){
console.log(this.name+'正在吃'+food);
}
}
方法一
原型链继承
通过new一个空的对象,这个空对象指向Animal并且Cat.prototype指向了这个空对象
特点: 基于原型链,既是父类实例,也是子类的
缺点: 无法实现多继承
function Cat(){}
Cat.prototype = new Animal();
Cat.prototype.name = 'cat';
var cat = new Cat();
console.log(cat.name) //cat
console.log(cat.eat('fish')) //cat正在吃fish
方法二
构造继承
使用父类的构造函数来增强子类实例,等于是复制了父类的实例给子类
特点: 可以实现多继承
缺点: 只能继承父类实例的属性和方法,不能继承原型上的属性和方法
function Bir(name){
Animal.call(this);
this.name = name|| "Tom";
}
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true
方法三
组合继承
相当于构造继承和原型链继承的组合体。通过调用父类构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用
特点:可以继承实例属性/方法,也可以继承原型属性/方法
缺点:调用了两次父类构造函数,生成了两份实例
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
// Test Code
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true
方法四
寄生组合继承
通过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性
function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
(function()
{
//创建一个没有实例方法的类
var Super = function(){};
Super.prototype = Animal.prototype;
//将实例作为子类的原型
Cat.prototype = new Super();
}
)();
var cat = new Cat();
console.log(cat.name);
console.log(cat.sleep());
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true