How to add mixins to ES6 javascript classes?

2019-02-01 23:59发布

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 correct.

class Test {
  constructor() {
    this.var1 = 'var1'
  }
  method1() {
    console.log(this.var1)
  }
  test() {
    this.method2()
  }
}

var mixin = {
  var2: 'var2',
  method2: {
    console.log(this.var2)
  }
}

If I run (new Test()).test(), it will fail because there's no method2 on the class, as it's in the mixin, that's why I need to add the mixin variables and methods to the class.

I see there's a lodash mixin function https://lodash.com/docs/4.17.4#mixin, but I don't know how I could use it with ES6 classes. I'm fine with using lodash for the solution, or even plain JS with no libraries to provide the mixin functionality.

2条回答
等我变得足够好
2楼-- · 2019-02-02 00:26

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);
查看更多
叛逆
3楼-- · 2019-02-02 00:31

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.

查看更多
登录 后发表回答