Last active
September 12, 2016 01:06
-
-
Save JVMartin/6fbaddf278637cd705366cb9878c233f to your computer and use it in GitHub Desktop.
Private data from public methods in stampit
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
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()); |
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
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