Javascript Composition Over Inheritance
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 { |
以Factory改寫:
const dog = () => { |
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) => ({ |
const murderRobotDog = (name) => { |
可以注意到的是,Composition比起多重繼承有更大的彈性,繼承需要在一開始就設計好整個繼承架構,而Composition則是可以在任何時候疊加上去即可
在JS中可以多多利用Composition
Render by hexo-renderer-org with Emacs 25.2.1 (Org mode 8.2.10)