Here are my needs:
- Share functions / variables across multiple JavaScript classes.
- There is no mixin / module or multiple inheritance in JavaScript.
CoffeeScript does not solve this problem very well, but there is an interesting mixin pattern in CoffeeScript Cookbook » Mixins for classes, which introduces a new mixin
function that combines two classes into a new (anonymous) class, and have the new class extended from that class. The cons is that when any of those classes is changed, those changes won't be reflected in classes that have already included the mixins previously.
Making Mixin from Scratch
I then found a post by Addy Osmani Learning JavaScript Design Patterns > Mixin Pattern, in which he implements mixin pattern with _.extend
from Underscore / Lo-Dash. Seems to be a working solution.
Like this:
# concern.js.coffee
Function::include = (mixin) ->
_.extend(this.prototype, mixin)
# duck.js.coffee
this.Duck =
quake: ->
"quake quake"
walk: ->
"walks like a duck"
# yazi.js.coffee
class Yazi # "duck" in Chinese
@include Duck
# kamo.js.coffee
class Kamo
@include Duck
# app.js.coffee
yazi = new Yazi()
kamo = new Kamo()
yazi.quake() #=> "quake"
kamo.quake() #=> "quake"
The functions / variables from mixins are also overridable.
However whenever a change is made in the original mixin, they're not reflected in the classes that includes mixins, either -- same as the first method.
Note that because we're using CoffeeScript, it looks elegant like @include
. In JavaScript it would be a little bit verbose. Here is what CoffeeScript compiles:
// kamo.js
var Kamo = (function() {
var Kamo = function() {};
Kamo.include(Duck);
return Kamo;
})();
var kamo = new Kamo();
kamo.quake(); //=> "quake"
Adding Features from ActiveSupport::Concern
For example, the included
callback and classFunctions
:
# concern.js.coffee
Function::include = (mixin) ->
functions = _.omit(mixin, "included", "classFunctions")
_.extend(this.prototype, functions)
_.extend(this, mixin.classFunctions) # insert class functions in class itself
# Call "included" callback function if available
if typeof mixin.included is "function"
# call included(mixin, base)
# this = the mixin included, base = the class which called `include`
mixin.included.call(mixin, this)
# duck.js.coffee
this.Duck =
quake: ->
"quake quake"
walk: ->
"walks like a duck"
included: (base) ->
console.log "mixing this class as a duck: #{base}"
classFunctions:
kindOfDuck: -> true
# kamo.js.coffee
class Kamo
@include Duck
// app.js
// Console prints "mixing this class as a duck: function Kamo() { ..."
Kamo.kindOfDuck() //=> true
var animal = new Kamo()
animal.quake() //=> "quake quake"
However I have no idea how to make it like Concerning in Rails 4.1.
This is a post from my Blog, originally in Chinese. http://blog.yorkxin.org/posts/2014/06/10/mixin-and-concern-in-javascript