Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

A blend of CoffeeScript classes


May 09, 2021 CoffeeScript


Table of contents


The mix of classes

Problem

You have some common methods that you want to include in many different classes.

Solution

Using the mixOf library function, it generates a mixed parent class.

mixOf = (base, mixins...) ->
  class Mixed extends base
  for mixin in mixins by -1 #earlier mixins override later ones
    for name, method of mixin::
      Mixed::[name] = method
  Mixed

...

class DeepThought
  answer: ->
    42

class PhilosopherMixin
  pontificate: ->
    console.log "hmm..."
    @wise = yes

class DeeperThought extends mixOf DeepThought, PhilosopherMixin
  answer: ->
    @pontificate()
    super()

earth = new DeeperThought
earth.answer()
# hmm...
# => 42

Discuss

This applies to lightweight blending. S o you can inherit methods from the ancestors of the base and base classes, or you can inherit from the base classes and ancestors of the mixed classes, but you can't inherit from the ancestors of the mixed classes. At the same time, after a mixed class is declared, subsequent changes to the hybrid class are not reflected.