JSOOP 继承的坑——好的组合胜过继承(mixins、Object.assign())

139 阅读1分钟

应该避免多层继承,可以将一些简单的对象组合成新的对象。

const canEat = {
  eat: function() {
    this.hunger--
    console.log('eatting')
  }
}
const canWalk = {
  walk: function() {
    console.log('walking')
  }
}
function Person() {

}
Object.assign(Person.prototype, canEat, canWalk)
const p = new Person()
console.log(p)

  •  不同行为对象组合不同对象
const canEat = {
  eat: function() {
    this.hunger--
    console.log('eatting')
  }
}
const canWalk = {
  walk: function() {
    console.log('walking')
  }
}
const canSwim = {
  swim: function() {
    console.log('swim')
  }
}
function Person() {

}
Object.assign(Person.prototype, canEat, canWalk)
const p = new Person()
console.log(p)
function Goldfish() {}
Object.assign(Goldfish.prototype, canEat, canSwim)
const goldfish = new Goldfish()
console.log(goldfish)

  •  使用mixin
function mixin(target, ...sources) {
  Object.assign(target, ...sources)
}
const canEat = {
  eat: function() {
    this.hunger--
    console.log('eatting')
  }
}
const canWalk = {
  walk: function() {
    console.log('walking')
  }
}
const canSwim = {
  swim: function() {
    console.log('swim')
  }
}
function Person() {

}
mixin(Person.prototype, canEat, canWalk)
const p = new Person()
console.log(p)
function Goldfish() {}
mixin(Goldfish.prototype, canEat, canSwim)
const goldfish = new Goldfish()
console.log(goldfish)