类的继承方式

140 阅读1分钟

创建一个类

function Amnimal(name){
  this.name=name||'Amnimal'
  // 实例方法
  this.sleep=function(){
    console.log(this.name+'在睡觉')
  }
}
Amnimal.prototype.eat=function(food){
  console.log(this.name+'在吃'+food)
}

一.原型链继承

function Cat(){}
Cat.prototype=new Amnimal()
Cat.prototype.name='cat';
var cat = new Cat();
console.log(cat.name)
console.log(cat.sleep())
console.log(cat.eat('fish'))

缺点:无法实现多继承

二.构造函数继承

function Cat(name){
  Amnimal.call(this);
  this.name=name||'TOM'
}
var cat =new Cat()
console.log(cat.name)
console.log(cat.sleep())
console.log(cat.eat('fish'))

缺点:只能继承父类实例的属性和方法,不能继承原型上的属性和方法

三.组合继承:相当于构造继承和原型链继承的组合体。通过调用父类构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用

function Cat(name){
 Amnimal.call(this)
 this.name=name||'Jack'
}
Cat.prototype=new Amnimal();
Cat.prototype.constructor = Cat
var cat =new Cat()
console.log(cat.name)
console.log(cat.sleep())
console.log(cat.eat('fish'))

缺点:调用了两次父类构造函数,生成了两份实例

四.寄生组合继承:通过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性(常用的方法)

function Cat(name){
  Amnimal.call(this);
  this.name = name || 'huahua';
}
function Super(){};
Super.prototype = Amnimal.prototype;
Cat.prototype =new Super()
var cat = new Cat()
console.log(cat.name)
console.log(cat.sleep())
console.log(cat.eat('fish'))

还有实例继承和拷贝继承,实用性不强,就不一一列举了,我们最常用的就是寄生组合继承方式,推荐!