【问题标题】:How to merge instead of replace object when extend扩展时如何合并而不是替换对象
【发布时间】:2024-01-23 23:47:01
【问题描述】:
class A
  constructor:
    //dosomething
  loadFunctions:
    loadDrillingCharges: (memoize) ->


class B extends A
  constructor:
    super()
  loadFunctions:
    loadLockDDR: (memoize) ->

(new B).loadFunctions 将是一个仅具有loadLockDDR 属性的对象

我希望(new B).loadFunctions 成为{ loadDrillingCharges: -> , loadLockDDR: -> }

我可以_.extend(B::loadFunctions, A::loadFunctions),但它并不优雅。

我尝试使用cocktail mixin,但它搞砸了 super()

我可以做些什么来合并扩展后的对象而不是搞砸 coffescript super。

【问题讨论】:

  • 我会简单地避免这种模式,并使用您已经在使用 load 的前缀。

标签: javascript inheritance coffeescript mixins


【解决方案1】:

CoffeeScript 本身并不支持 Mixin,原因很充分: 它们可以自己简单地实现。例如,这里有两个函数, extend() 和 include(),它们将分别向类添加类和实例属性:

extend = (obj, mixin) ->
 obj[name] = name 方法,mixin 方法
 对象

包括=(klass,mixin)->
 扩展 klass.prototype,mixin

# 用法
包括鹦鹉,
 已故:真

(新鹦鹉).isDeceased

【讨论】:

    【解决方案2】:

    不是很性感,但是……

    class A
      constructor: ->
        # dosomething
      loadFunctions: ->
        loadDrillingCharges: (memoize) ->
    
    
    class B extends A
      constructor: ->
        super()
      loadFunctions: ->
        do (that=super()) ->
          that.loadLockDDR = (memoize) ->
          that
    
    console.log (new A).loadFunctions()
    console.log (new B).loadFunctions()
    

    制作:

    { loadDrillingCharges: [Function] }
    { loadDrillingCharges: [Function], loadLockDDR: [Function] }
    

    【讨论】: