Javascript中Composition示範code
當在javascript中需要多重繼承概念時可考慮使用Composition

1 Factory functions

Compare to prototype factory function is a more flexible way to create object using JS.

OO形式(using prototype):

class Dog {
constructor() {
this.sound = 'woof'
}
talk() {
console.log(this.sound)
}
}
const sniffles = new Dog()
sniffles.talk() // Outputs: "woof"

以Factory改寫:

const dog = () => {
const sound = 'woof'
return {
talk: () => console.log(sound)
}
}
const sniffles = dog()
sniffles.talk() // Outputs: "woof"

2 Composition

假設我們想建立以下物件關係

dog            = pooper + barker //dog can poop and bark
cat            = pooper + meower //cat can poop and meow
cleaningRobot  = driver + cleaner //cleaningRobot can be driven and clean
murderRobot    = driver + killer
murderRobotDog = driver + killer + barker

以上需求可使用prototype多重繼承達成,但在javascript中我們也可用Composition來處理,以下範例使用到上述的Factory

const barker = (state) => ({
bark: () => console.log('Woof, I am ' + state.name)
})
const driver = (state) => ({
drive: () => state.position = state.position + state.speed
})
const murderRobotDog = (name)  => {
let state = {
name,
speed: 100,
position: 0
}
return Object.assign(
{},
barker(state),
driver(state),
killer(state)
)
}
const bruno = murderRobotDog('bruno')
bruno.bark() // "Woof, I am Bruno"

可以注意到的是,Composition比起多重繼承有更大的彈性,繼承需要在一開始就設計好整個繼承架構,而Composition則是可以在任何時候疊加上去即可
在JS中可以多多利用Composition

Last Updated 2017-03-10 五 10:26.
Render by hexo-renderer-org with Emacs 25.2.1 (Org mode 8.2.10)