Skip to content Skip to sidebar Skip to footer

How To Add Mixins To Es6 Javascript Classes?

In an ES6 class with some instance variables and methods, how can you add a mixin to it? I've given an example below, though I don't know if the syntax for the mixin object is corr

Solution 1:

Javascript's object/property system is much more dynamic than most languages, so it's very easy to add functionality to an object. As functions are first-class objects, they can be added to an object in exactly the same way. Object.assign is the way to add the properties of one object to another object. (Its behaviour is in many ways comparable to _.mixin.)

Classes in Javascript are only syntactic sugar that makes adding a constructor/prototype pair easy and clear. The functionality hasn't changed from pre-ES6 code.

You can add the property to the prototype:

Object.assign(Test.prototype, mixin);

You could add it in the constructor to every object created:

constructor() {
    this.var1 = 'var1';
    Object.assign(this, mixin);
}

You could add it in the constructor based on a condition:

constructor() {
    this.var1 = 'var1';
    if (someCondition) {
        Object.assign(this, mixin);
    }
}

Or you could assign it to an object after it is created:

lettest = new Test();
Object.assign(test, mixin);

Solution 2:

In es6 you can do this without assigning and you can even invoke the mixin constructor at the correct time!

http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/#bettermixinsthroughclassexpressions

This pattern uses class expressions to create a new base class for every mixin.

letMyMixin = (superclass) => classextends superclass {
  foo() {
    console.log('foo from MyMixin');
  }
};
class MyClass extends MyMixin(MyBaseClass){
  /* ... */
}

Solution 3:

You should probably look at Object.assign(). Gotta look something like this:

Object.assign(Test.prototype, mixin);

This will make sure all methods and properties from mixin will be copied into Test constructor's prototype object.

Post a Comment for "How To Add Mixins To Es6 Javascript Classes?"