Mixins in ECMAScript 6 - Awkward, inconvenient, powerful.

codelitically_incorrect profile image codelitically_incorrect ・2 min read

(UPDATE: I am really not sure about the state of proposals for 'mixins' in ECMAScript. The information below were snippets I got from another source in 2017. I do know we are able to support traits in ES6 by way of Object.assign(..) but I was hoping it would be keyworded-in as part of the class definition syntax for future ES. )

So you've heard that ECMAScript 6 will sport "Mixins". Some languages implement this feature as "Traits" or Shared Modules. The origin of the concept, I feel, was born in the language called SELF (a Sun Microsystems experiment, see: http://www.selflanguage.org/).

In a simple explanation, traits, or mixins, is a language feature allowing classes of objects to share a common set of behaviors we call methods -- or functions, perhaps even data properties. It is NOT inheritance, but some think of it as multiple inheritance. It is an arbitrary implementation for simple code reuse when inheritance does not make sense.

For example:
In building a game, the Character, Level or Weapon classes might all posses the ability to log messages to a console for debugging purposes, so a mixin called Loggable could be used to package up a few methods to be shared across the class hierarchy. This way, classes even though not related, might share this common trait. As you see, inheritance does not make sense logically or semantically. A Person is-not a Loggable. It does not sound right, it does not read right, it conflicts with the beauty of code and clarity.

here is the Ruby representation. It's a beauty.

module Loggable
   def log (msg)
      puts msg

class Character include Loggable
   def jump

class Sword < Weapon  include Loggable
   def animate_blade
      log("do sword animation");

In Scala, It's a beauty:

class Sword extends Weapon with Loggable {
   def animate_blade() { 
      log("do sword animation")

In ECMAScript 6:

var Loggable = Base => class extends Base {
  log(s) { }
class Weapon { }
class Sword extends Loggable(Weapon) { }

It gets ugly if you wanted 2 or more mix-ins:

class Weapon { }
class Sword extends Loggable(Localizable(Weapon)) { }

I don't know. It's powerful. Definitely not a beauty!

Posted on by:


markdown guide