Last Updated: July 05, 2016
·
3.883K
· haihappen

Mixins in CoffeeScript

Somebody will send me straight to Hell for this madness, but it works! :)

Function::include = (mixin) ->
  for name, method of mixin
    method['super'] = @prototype[name]
    @prototype[name] = method

class Foo
  foo: -> 'foo from Foo'

Mixin =
  foo: ->
    "#{arguments.callee.super()}, foo from Mixin"

class Bar extends Foo
  @includee Mixin # yes, intended typo, otherwise coderwall messes it all up (coderwall team, please help me)

new Bar().foo() # => "foo from Foo, foo from Mixin"

EDIT Renamed extend to include to avoid confusion for Rubists ;)

1 Response
Add your response

The whole 'super' thing breaks if you mix something in more than once as far as I can tell..

over 1 year ago ·