Ciel Ciel - 1 year ago 81
Javascript Question

Coffeescript/Javascript Mixins - Idiot Seeking Explanation

I have been reading up on

or just plain
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
variable? I'm not understanding what that is even doing.

2. Secondly, what is up with the
? 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;

Can anyone shed some general light on this?

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

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

class User extends Module
@extend ORM

Here is how I read this ...

  • create literal

  • Declare method
    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
has a method,
, and then
is implemented/extended by the 'class'
. So I take this to mean that
has the same shape as
. That part makes sense so far, simplistic inheritance. But then I get lost on
@extend ORM

is a method on
, but what is the
method doing? When is it called? How is it implemented?

Answer Source
  • extend copies the methods from the "module" object onto the object being extended
  • include copies the methods from the "module" object onto the prototype of the object being extended

1 The moduleKeywords is used to protect some methods of the module, so the are not copied to object, because they have special meaning

2 The extended?.apply(@) says that if the module has a property named extended than assume it's a function and then call this function having the "this" in the function equal to @, @ being the extended object, you can think of it as saying something like (although not quite, but it's just an intuition) @.extended() (@ == this in coffeescript)

"apply" function in JS
the existential operator in CS

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download