Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active January 25, 2016 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save branneman/7a200ded7d8ab4962760 to your computer and use it in GitHub Desktop.
Save branneman/7a200ded7d8ab4962760 to your computer and use it in GitHub Desktop.
JavaScript Mixins
/**
* Original class
*/
class Todo {
constructor(name) {
this.name = name || 'Untitled';
this.done = false;
}
do() {
this.done = true;
return this;
}
undo() {
this.done = false;
return this;
}
}
/**
* Compose mixin with original class
*/
class ColouredTodo extends Todo {}
// Solution 1: Object mixin
Object.assign(ColouredTodo.prototype, ColouredMixin);
// Solution 2: Functional mixin
ColouredMixin(ColouredTodo.prototype);
const ColouredMixin = {
setColourRGB({r, g, b}) {
this.colourCode = {r, g, b};
return this;
},
getColourRGB() {
return this.colourCode;
}
};
const ColouredMixin = target => {
Object.assign(target, {
setColourRGB({r, g, b}) {
this.colourCode = {r, g, b};
return this;
},
getColourRGB() {
return this.colourCode;
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment