Mixins

Mixins are not something supported natively by CoffeeScript, for the good reason that they can be trivially implemented yourself. For example, here’s two functions, extend() and include(), that’ll add class and instance properties respectively to a class:

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

Mixins are a great pattern for sharing common logic between modules when inheritance is not suitable. The advantage of mixins is that you can include multiple ones, compared to inheritance where only one class can be inherited from.

Get The Little Book on CoffeeScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.