Created
May 4, 2016 03:24
-
-
Save bbatliner/a4ed33fa0a8a72b576fc1c3cfe9dce90 to your computer and use it in GitHub Desktop.
I rewrote the examples from the stampit (https://github.com/stampit-org/stampit) readme in vanilla ES6. Great way to understand the inner machinations of Javascript!
This file contains 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
// Use a closure for data privacy | |
const a = function() { | |
const priv = 'a'; | |
return { | |
getA() { | |
return priv; | |
} | |
}; | |
}; | |
a(); // Object | |
a().getA(); // "a" | |
// Another one - note that `priv` is named the same in `a` and `b` | |
const b = function() { | |
const priv = 'b'; | |
return { | |
getB() { | |
return priv; | |
} | |
}; | |
}; | |
b(); // Object | |
b().getB(); // "b" | |
// Compose the two factories to create a third | |
const c = function() { | |
return Object.assign({}, a(), b()); | |
}; | |
const foo = c(); | |
foo.getA(); // "a" | |
foo.getB(); // "b" | |
// Another example: more private data | |
const availability = function() { | |
var isOpen = false; // private | |
return { | |
open() { | |
isOpen = true; | |
return this; | |
}, | |
close() { | |
isOpen = false; | |
return this; | |
}, | |
isOpen() { | |
return isOpen; | |
} | |
}; | |
}; | |
// A mixin with public methods and state | |
const membership = { | |
add(member) { | |
this.members[member.name] = member; | |
return this; | |
}, | |
getMember(name) { | |
return this.members[name]; | |
}, | |
members: {} | |
}; | |
// A mixin that represents some default values | |
const defaults = { | |
name: 'The Saloon', | |
specials: 'Whisky, Gin, Tequila' | |
}; | |
// Compose our mixins to create a bar! | |
const bar = function() { | |
return Object.assign({}, defaults, availability(), membership); | |
}; | |
// Override defaults with Object.assign | |
const myBar = Object.assign({}, bar(), {name: 'Moe\'s'}); | |
// Everything works! | |
myBar.add({name: 'Homer'}).open().getMember('Homer'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment