Skip to content

Instantly share code, notes, and snippets.

@jnvm
Last active February 5, 2018 06:18
Show Gist options
  • Save jnvm/4f026d9e0f61f780d5167106eee6a1d2 to your computer and use it in GitHub Desktop.
Save jnvm/4f026d9e0f61f780d5167106eee6a1d2 to your computer and use it in GitHub Desktop.
frozen weakmap encapsulation
/*
https://github.com/tc39/proposal-class-fields/blob/master/PRIVATE_SYNTAX_FAQ.md#how-can-you-model-encapsulation-using-weakmaps
"There's a potential pitfall with this approach, though"
...so prevent it!
*/
const Person = (function(){
const privates = new WeakMap;
let ids = 0;
return class Person {
constructor(name, makeGreeting) {
this.name = name;
privates.set(this,Object.freeze({id: ids++, makeGreeting}));//prevention
}
equals(otherPerson) {
return privates.get(this).id === privates.get(otherPerson).id;
}
greet(otherPerson) {
return privates.get(this).makeGreeting(otherPerson.name);
}
}
})();
let alice = new Person('Alice', name => `Hello, ${name}!`);
let bob = new Person('Bob', name => `Hi, ${name}.`);
alice.equals(bob); // false
alice.greet(bob); // === 'Hello, Bob!'
//At first glance this appears fine, but:
let mallory = new Person('Mallory', function(name) {this.id = 0; return `o/ ${name}`;});
mallory.greet(bob); // === 'o/ Bob'
mallory.equals(alice); // false. Phew!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment