Skip to content

Instantly share code, notes, and snippets.

@JVMartin
Last active September 12, 2016 01:06
Show Gist options
  • Save JVMartin/6fbaddf278637cd705366cb9878c233f to your computer and use it in GitHub Desktop.
Save JVMartin/6fbaddf278637cd705366cb9878c233f to your computer and use it in GitHub Desktop.
Private data from public methods in stampit
import User from './User';
const user_a = User();
const user_b = User();
console.log(user_a.getID());
console.log(user_a.getName());
console.log(user_b.getID());
console.log(user_b.getName());
import stampit from 'stampit';
let numUsers = 0;
let map = new WeakMap();
function setData(object, key, value) {
let data = map.get(object);
data[key] = value;
}
function getData(object, key) {
let data = map.get(object);
return data[key];
}
export default stampit().init(function() {
map.set(this, {});
setData(this, 'id', ++numUsers);
setData(this, 'name', 'User ' + getData(this, 'id'));
}).methods({
getID() {
return getData(this, 'id');
},
getName() {
return getData(this, 'name')
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment