扩展时如何合并而不是替换对象

时间:2014-07-17 05:30:32

标签: javascript inheritance coffeescript mixins

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。

2 个答案:

答案 0 :(得分:1)

Mixins不是CoffeeScript原生支持的东西,原因很简单 他们可以自己轻松实施。例如,这里有两个函数, extend()和include(),它们分别为类添加类和实例属性:

extend = (obj, mixin) ->
 obj[name] = method for name, method of mixin 
 obj

include = (klass, mixin) ->
 extend klass.prototype, mixin

# Usage
include Parrot,
 isDeceased: true

(new Parrot).isDeceased

答案 1 :(得分:0)

不是很性感,但是......

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] }