js ES5 原型链继承和组合继承

82 阅读1分钟

ES5 原型链继承和组合继承

子类借用父类构造函数继承父类对象属性

需要使用父类构造函数内原型方法时,需要子类__proto__原型对象指向父类实例,原型链会向上找,直到找到需要用到的父类方法。

function Vechile (brandNo, price) {
  console.log("this:", this); // this: Bus{} 指向 Bus 实例对象
  this.brandNo = brandNo;
  this.price = price;
}

Vechile.prototype.sale = function () {
  console.log(this + " 销售");
}

function Bus (brandNo, price, seatNo) {
  Vechile.apply(this, [brandNo, price]); // 借用构造函数继承
  this.seatNo = seatNo;
}

// 原型链继承
Bus.prototype = new Vechile;
Bus.prototype.constructor = Bus;

let bus = new Bus("大巴", 20, 64);
bus.sale();


function Car (brandNo, price, type) {
  Vechile.apply(this, [brandNo, price]);
  this.seatNo = type;
}

上方的代码父类实例调用了两次,下方改进一下

function Vechile (brandNo, price) {
  console.log("this:", this);
  this.brandNo = brandNo;
  this.price = price;
}

Vechile.prototype.sale = function () {
  console.log(this + " 销售");
}

function Bus (brandNo, price, seatNo) {
  Vechile.apply(this, [brandNo, price]); // 借用构造函数继承
  this.seatNo = seatNo;
}

// 组合继承
function protoExtendsWithMdl (ParentClass, SonClass) {
  function Middle () {
    this.constructor = SonClass;
  }
  Middle.prototype = ParentClass.prototype;
  SonClass.prototype = new Middle();
}

protoExtendsWithMdl(Vechile, Bus)

let bus = new Bus("大巴", 20, 64);
console.log(bus);
bus.sale();


function Car (brandNo, price, type) {
  Vechile.apply(this, [brandNo, price]);
  this.seatNo = type;
}