Last active
January 25, 2016 18:40
-
-
Save branneman/7a200ded7d8ab4962760 to your computer and use it in GitHub Desktop.
JavaScript Mixins
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ColouredMixin = { | |
setColourRGB({r, g, b}) { | |
this.colourCode = {r, g, b}; | |
return this; | |
}, | |
getColourRGB() { | |
return this.colourCode; | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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