Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  106] [ 4]  / answers: 1 / hits: 24606  / 7 Years ago, wed, february 15, 2017, 12:00:00

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.


More From » node.js

 Answers
18

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);

[#58929] Monday, February 13, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
albert

Total Points: 652
Total Questions: 105
Total Answers: 108

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;