zlx362211854 / daily-study

每日一个知识点总结,以issue的形式体现
10 stars 6 forks source link

129. js如何多继承? #186

Open zlx362211854 opened 4 years ago

goldEli commented 4 years ago

用类装饰器,模拟实现多继承:

// base class
class A {  
  foo() {
    console.log(`from A -> inside instance of A: ${this instanceof A}`);
  }
}

// B mixin, will need a wrapper over it to be used
const B = (B) => class extends B {
  foo() {
    if (super.foo) super.foo(); // mixins don't know who is super, guard against not having the method
    console.log(`from B -> inside instance of B: ${this instanceof B}`);
  }
};

// C mixin, will need a wrapper over it to be used
const C = (C) => class extends C {
  foo() {
    if (super.foo) super.foo(); // mixins don't know who is super, guard against not having the method
    console.log(`from C -> inside instance of C: ${this instanceof C}`);
  }
};

// D class, extends A, B and C, preserving composition and super method
class D extends C(B(A)) {  
  foo() {
    super.foo();
    console.log(`from D -> inside instance of D: ${this instanceof D}`);
  }
}

const test = new D()
test.foo()

// from A -> inside instance of A: true
// from B -> inside instance of B: true
// from C -> inside instance of C: true
// from D -> inside instance of D: true

Reference

ES6 Class Multiple inheritance

zlx362211854 commented 4 years ago

多继承就是一个子类继承的属性和方法同时继承自多个父类。举个例子

function Mother(quotient) {
  this.gender = 'female'
  this.quotient = quotient
}
function Father(height) {
  this.gender = 'male'
  this.height = height
}

现在我想要一个Child构造函数,同时继承Mother和Father的所有属性,可以用call或apply来实现多继承:

function Mother(quotient) {
  this.gender = 'female'
  this.quotient = quotient
}
function Father(height) {
  this.gender = 'male'
  this.height = height
}

function Child(height, quotient) {
  Father.call(this, height)
  Mother.call(this, quotient)
}
var girl = new Child(165, 90)
console.log(girl)
// Child {gender: "female", height: 165, quotient: 90}