JavaScript 原型继承,构造继承,实例继承,组合继承,寄生组合继承

90 阅读1分钟

继承

关于继承有很多的方式:本文介绍五种方式

这里定义父类为Animal,子类为Cat

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() {}

1、原型继承

将父类的实例作为子类的原型

function Cat() {}
Cat.prototype = new Animal();

2、构造继承

使用父类的构造器来增强子类实例

function Cat(name) {
  Animal.call(this, name);
}
const mao = new Cat("蓝莓");
console.log(mao);

3、实例继承

为父类实例添加新特性,作为子类的实例返回

function Cat() {
  const animal = new Animal()
  animal.play = function(playName) {
    console.log('玩' + playName)
  }
  Object.assign(this, animal)
}

4、组合继承

结合原型链继承和借用构造函数继承组合起来实现的继承;

通过父类构造,继承父类的属性并保留传参,然后通过奖父类实例作为子类原型,实现函数复用

function Cat(args) {
  Animal.call(this, args);
}
Cat.prototype = new Animal();

const mao4 = new Cat("哈基米");
console.log(mao4, mao4.eat('鱼罐头'));

5、寄生组合继承(最优)

结合原型链继承和构造函数继承的方法,同时自己创建一个对象,并且让这个对象的原型指向父类构造函数的prototype,实现寄生组合继承

function Cat(args) {
  Animal.call(this, args);
}

function clone(parent, child) {
  child.prototype = Object.assign(parent.prototype);
  child.prototype.constructor = child;
}
clone(Animal, Cat);

const mao5 = new Cat("小哈");
mao5.age = 12;
mao5.get = function () {
  console.log(this.name);
};

// 测试数据
const mao6 = new Cat("哈基米");
mao6.age = 13;
console.log(mao6.age)  // 13
mao5.get();   // 哈基米
mao5.eat("饭");   // 哈基米正在吃饭
mao6.sleep();   // 哈基米正在睡觉!