How to add mixins to ES6 javascript classes?

前端 未结 3 833
再見小時候
再見小時候 2020-12-13 15:08

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 objec

相关标签:
3条回答
  • 2020-12-13 15:44

    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:

    let test = new Test();
    Object.assign(test, mixin);
    
    0 讨论(0)
  • 2020-12-13 16:07

    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.

    let MyMixin = (superclass) => class extends superclass {
      foo() {
        console.log('foo from MyMixin');
      }
    };
    
    class MyClass extends MyMixin(MyBaseClass) {
      /* ... */
    }
    
    0 讨论(0)
  • 2020-12-13 16:09

    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.

    0 讨论(0)
提交回复
热议问题