Last active
August 29, 2015 14:17
-
-
Save nickfargo/976f5ec5139065c70ed7 to your computer and use it in GitHub Desktop.
Privacy via WeakMap
This file contains hidden or 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
| 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; | |
| } | |
| }; |
This file contains hidden or 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 {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); } | |
| } |
This file contains hidden or 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 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