Skip to content

Instantly share code, notes, and snippets.

@MichalZalecki
Last active May 29, 2016 19:23
Show Gist options
  • Save MichalZalecki/09a4632acfe2c0745c0ede29ad29a7d2 to your computer and use it in GitHub Desktop.
Save MichalZalecki/09a4632acfe2c0745c0ede29ad29a7d2 to your computer and use it in GitHub Desktop.
Multiple mixins by using extends/decorators/virtual methods/stamps
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
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!"
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!
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