js继承方式

7 阅读1分钟

1、原型链继承

通过将子类的原型(prototype)指向父类父类实例

function animals() {
  this.type = '飞禽'
}
function children(name) {
  this.name = name;
}
children.prototype = new animals();
children.prototype.fly = function (value) {
  console.log(this.type + this.name + value);
}
const child = new children('大雁');
child.fly("能跑");

2、构造函数继承

构造函数继承是通过在子类的构造函数中调用父类的构造函数来实现的。

function animals() {
  this.type = '飞禽'
}
function children(name) {
  animals.call(this);
  this.name = name;
  this.fly = function (value) {
    console.log(this.type + this.name+value);
  }
}
const child = new children('大雁');
child.fly("能跑");
  • 优点是每个实例都有自己的属性,不会共享父类的属性,
  • 缺点但不能继承父类的原型方法。
function animals() {
  this.type = '飞禽'
}
animals.prototype.fly1 = function (value) {
  console.log(this.type + value);
}
function children(name) {
  animals.call(this);
  this.name = name;
}
const child = new children('大雁');
child.fly1("能跑"); // 会报错

3、组合继承

组合继承融合了原型链继承和构造函数继承

function animals() {
  this.type = '飞禽'
}
animals.prototype.fly1 = function (value) {
  console.log(this.type+this.name + value);
}
function children(name) {
  animals.call(this);
  this.name = name;
}

children.prototype = new animals();
children.prototype.constructor = children;
const child = new children('大雁');
child.fly1("能跑");

缺点是调用两次父类构造函数,开销较大。

4、寄生组合继承

function animals() {
  this.type = '飞禽'
}
animals.prototype.fly1 = function (value) {
  console.log(this.type+this.name + value);
}
function children(name) {
  animals.call(this);
  this.name = name;
}
children.prototype = Object.create(animals.prototype);
children.prototype.constructor = children;
const child = new children('大雁');
child.fly1("能跑");

与组合继承的区别在于使用了 Object.create方法,避免了调用父类两次的问题

5、ES6的class

class Animals{
  constructor() {
    this.type = '飞禽'
  }
}

class Children extends Animals{
  constructor(name) {
    super();
    this.name = name;
  }
  fly (value) {
    console.log(this.type + this.name + value);
  }
}
const child = new Children('大雁');
child.fly("能跑");