Last active
May 29, 2016 19:23
-
-
Save MichalZalecki/09a4632acfe2c0745c0ede29ad29a7d2 to your computer and use it in GitHub Desktop.
Multiple mixins by using extends/decorators/virtual methods/stamps
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
function hi() { | |
console.log(`Hi ${this.name}!`); | |
} | |
function by() { | |
console.log(`By ${this.name}!`); | |
} | |
function mixin(fn, name = fn.name) { | |
return target => { | |
target.prototype[name] = fn; | |
}; | |
} | |
@mixin(by) | |
@mixin(hi) | |
class Person { | |
constructor(name) { | |
this.name = name; | |
} | |
} | |
const p = new Person("Michal"); | |
p.hi(); // "Hi Michal!" | |
p.by(); // "By Michal!" | |
// Check decorators proposal https://github.com/wycats/javascript-decorators | |
// Check https://github.com/jayphelps/core-decorators.js if you are using decorators |
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 HiMixin = Sup => class extends Sup { | |
hi() { | |
console.log(`Hi ${this.name}!`); | |
} | |
}; | |
const ByMixin = Sup => class extends Sup { | |
by() { | |
console.log(`By ${this.name}!`); | |
} | |
}; | |
class Person extends HiMixin(ByMixin(class {})) { | |
constructor(name) { | |
super(name); | |
this.name = name; | |
} | |
} | |
const p = new Person("Michal"); | |
p.hi(); // "Hi Michal!" | |
p.by(); // "By Michal!" |
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
import stampit from "stampit"; | |
function hi() { | |
console.log(`Hi ${this.name}!`); | |
} | |
function by() { | |
console.log(`By ${this.name}!`); | |
} | |
const Person = stampit().methods({ hi, by }); | |
const p = Person({ name: "Michal" }); | |
p.hi(); // "Hi Michal!" | |
p.by(); // "By Michal! |
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
function hi() { | |
console.log(`Hi ${this.name}!`); | |
} | |
function by() { | |
console.log(`By ${this.name}!`); | |
} | |
function mixin(fn, name = fn.name) { | |
return { ...this, [name]: fn }; | |
} | |
const p = { name: "Michal" }::mixin(by)::mixin(hi); | |
p.hi(); // "Hi Michal!" | |
p.by(); // "By Michal!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment