Skip to content

Instantly share code, notes, and snippets.

@bbatliner
Created May 4, 2016 03:24
Show Gist options
  • Save bbatliner/a4ed33fa0a8a72b576fc1c3cfe9dce90 to your computer and use it in GitHub Desktop.
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!
// 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