Skip to content

Instantly share code, notes, and snippets.

@nickfargo
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save nickfargo/976f5ec5139065c70ed7 to your computer and use it in GitHub Desktop.

Select an option

Save nickfargo/976f5ec5139065c70ed7 to your computer and use it in GitHub Desktop.
Privacy via WeakMap
let _ = new WeakMap;
export default {
init: function (obj, map = {}) {
_.set(obj, map);
},
get: function (obj, key) {
return _.get(obj)[key];
},
set: function (obj, key, value) {
return _.get(obj)[key] = value;
}
};
import {init, get, set} from 'privacy'
export default class Employee {
constructor (name, title) {
init(this, {name, title});
}
get name () { return get(this, 'name'); }
get title () { return get(this, 'title'); }
set title (value) { return set(this, 'title', value); }
}
import Employee from 'employee'
let a = new Employee('Malory', 'CEO');
let b = new Employee('Cyril', 'Accountant');
let c = new Employee('Carol', 'Secretary');
a.name; // "Malory"
a.title; // "CEO"
b.name; // "Cyril"
b.title; // "Accountant"
b.title = "VP"; // "VP"
c.name; // "Carol"
c.title; // "Secretary"
c.name = "Sheryl"; // Error (property is read-only)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment