[nodejs]CoffeeScript里实现Mixin

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

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

 CoffeeScript里kclass.prototype还可以写成kclass::, 今天在CoffeeScript in action一书里也看到了类似的一种写法

class Mixin
    constructor: (methods) ->
        for own k,v of methods
            @[k]=v

   #定义include,把所有的方法加入到Target的类里
    include: (kclass) -> 
        for own k,v of @
            kclass::[k] =v

上面是定义了一个Mixin的类,constructor 用来记住要混入的方法,include方法则把他们加入到指定类的prototype中去。

new_mixin = new Mixin
    method1: -> console.log 'method1'
    method2: -> console.log 'method2'


class TestClass
    new_mixin.include @  #这样给TestClass加入了2个新方法, 在CoffeeScript里@就是this的意思

o = new TestClass 
o.method1() # method1
原文地址:https://www.cnblogs.com/buhaiqing/p/3082008.html