Skip to content

Instantly share code, notes, and snippets.

@afeld
Last active December 17, 2015 22:09
Show Gist options
  • Save afeld/5680195 to your computer and use it in GitHub Desktop.
Save afeld/5680195 to your computer and use it in GitHub Desktop.
CoffeeScript mixins
# a.k.a. _.extend()
extend = (obj, mixin) ->
for name, method of mixin
obj[name] = method
include = (klass, mixin) ->
extend klass.prototype, mixin
MyMixin =
foo: -> 'bar'
## external ##
class User
include User, MyMixin
u = new User()
alert u.foo()
## internal ##
class Base
@include: (mixin) ->
include @, mixin
class Post extends Base
Post.include MyMixin
p = new Post()
alert p.foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment