5. oop继承

2019-11-28  本文已影响0人  zdxhxh

JavaScript 继承实现方式

A. 类式继承

所谓类式继承,就是将子类的原型指向父类的一个实例。这样优缺点就是

// 父类
function Parent(name) {
  this.name = name;
}
Parent.prototype.sayYes = function () {
  console.log("say yes");
};
// 子类
function Child(name) {
  this.bName = name;
}
Child.prototype = new Parent();
let child = new Child("b");

B. 构造函数继承

为了继承父类的构造函数,我们决定在子类的constructor使用call方法调用父组件的构造函数

// 父类
function Parent(name) {
  this.name = name;
}
// 子类
function Child(aName, bName) {
  Parent.call(this, aName);
  this.bName = bName;
}

C. 组合继承

组合继承就是同时使用上面两种继承方法

// 父类
function Parent(name) {
  this.name = name;
}
Parent.prototype.sayYes = function () {
  console.log("say yes");
};
// 子类
function Child(name, bName) {
  Parent.call(this, name);
  this.bName = bName;
}
Child.prototype = new Parent();
let child = new Child("b", "a");

D. 寄生继承

为了解决继承原型方法而实例化父类作为子类Prototype而浪费内存的问题,06 年道格拉斯 \* 克罗斯创造了寄生继承,实现方式是我们自己创建一个构造函数,然后将它的原型对象指向要继承的对象

function inheritClass(childClass, parentClass) {
  function P() {}
  P.prototype = parentClass.prototype;
  let p = new P();
  p.constructor = childClass;
  childClass.prototype = p;
}

为什么不让 childClass.prototype = Parent.prototype,很多写继承的博客都没有写到这一点,很明显,这是因为这样做,当子类扩展原型方法时,就会污染父类的原型方法,所以必须子类原型必须是一个新的实例。

E. 寄生组合式继承

function A() {}
A.prototype.sayHello = function () {
  console.log("hello world");
};
function B() {
  A.call(this);
}
inheritClass(B, A);
上一篇下一篇

猜你喜欢

热点阅读