CoffeeScript 類的混合

2022-06-29 16:46 更新

類的混合

問題

你有一些通用方法,你想把他們包含到很多不同的類中。

解決方案

使用mixOf庫函數(shù),它會(huì)生成一個(gè)混合父類。

mixOf = (base, mixins...) ->
  class Mixed extends base
  for mixin in mixins by -1 #earlier mixins override later ones
    for name, method of mixin::
      Mixed::[name] = method
  Mixed

...

class DeepThought
  answer: ->
    42

class PhilosopherMixin
  pontificate: ->
    console.log "hmm..."
    @wise = yes

class DeeperThought extends mixOf DeepThought, PhilosopherMixin
  answer: ->
    @pontificate()
    super()

earth = new DeeperThought
earth.answer()
# hmm...
# => 42

討論

這適用于輕量級(jí)的混合。因此你可以從基類和基類的祖先中繼承方法,也可以從混合類的基類和祖先中繼承,但是不能從混合類的祖先中繼承。與此同時(shí),在聲明了一個(gè)混合類后,此后的對(duì)這個(gè)混合類進(jìn)行的改變是不會(huì)反應(yīng)出來的。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)