Coffeescript/Javascript Mixins – Idiot Seeking Explanation

Programming in javascript: Coffeescript/Javascript Mixins – Idiot Seeking Explanation on newest questions tagged javascript – Stack Overflow

I preface this by saying my Javascript experience is very weak. Lots of jQuery, very little real comprehension. I have read numerous books on javascript and, while I am not a poor programmer, the prototypal nature of Javascript just does not click with my brain.

I have been reading up on Mixins using Coffeescript or just plain Javascript from the following sources … (near the bottom)


And while I am able to compile the various examples, I have a major question that seems to be preventing me from making progress in comprehending them.

I have no idea what in the world is going on …

To start, I will explain the coffeescript that is confusing me…

moduleKeywords = ['extended', 'included']

    class Module
      @extend: (obj) ->
        for key, value of obj when key not in moduleKeywords
          @[key] = value


      @include: (obj) ->
        for key, value of obj when key not in moduleKeywords
          # Assign properties to the prototype
          @::[key] = value


A number of questions come up here.

1. First of all, what are we accomplishing with the moduleKeywords variable? I’m not understanding what that is even doing.

2. Secondly, what is up with the extended?.apply(@)? What is really going on here? I can look at the javascript compilation and see the following code ..

Module.extend = function(obj) {
      var key, value, _ref;
      for (key in obj) {
        value = obj[key];
        if (, key) < 0) {
          this[key] = value;
      if ((_ref = obj.extended) != null) {
      return this;

Say what? Can anyone shed some general light on this?

From deeper down in The Little Book on Coffeescript, I see an implementation.

ORM = 
  find: (id) ->
  create: (attrs) ->
  extended: ->
      save: -> 

class User extends Module
  @extend ORM

Here is how I read this …

  • create literal ORM.
  • Declare method find accepting a parameter.
  • Declare method ‘create’ accepting a parameter.
  • Declare method ‘extended’, with sub-method ‘include’, with sub-method ‘save’.

This is where I get the most lost.

The literal ORM has a method, extended, and then Module is implemented/extended by the ‘class’ User. So I take this to mean that User has the same shape as Module. That part makes sense so far, simplistic inheritance. But then I get lost on @extend ORM.

@extend is a method on Module, but what is the extended method doing? When is it called? How is it implemented?

Can anyone assist me in clearing some of this up?

See Answers

Programming in javascript: programming-in-javascript

Leave a Reply