Created
April 28, 2018 12:26
-
-
Save nairihar/d0acbb4211f611a5bcc8cc376db1ac5a to your computer and use it in GitHub Desktop.
Privates in JavaScript WeakMap, medium, using WeakMap, es6
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
const _state = new WeakMap() | |
const _addBalance = new WeakMap() | |
const _logBankChange = new WeakMap() | |
export default class Bank { | |
constructor() { | |
// public variables | |
this.name = 'B7' | |
// private variables | |
let _privateData = { | |
balance: 0, | |
logs: [] | |
} | |
_state.set(this, _privateData) | |
// private methods | |
_addBalance.set(this, (count) => { | |
_logBankChange.get(this)('add', count) | |
const _privateData = _state.get(this) | |
_privateData.balance += count | |
_state.set(this, _privateData) | |
}) | |
_logBankChange.set(this, (type, count) => { | |
const _privateData = _state.get(this) | |
_privateData.logs.push({ type, count }) | |
_state.set(this, _privateData) | |
}) | |
} | |
// public methods | |
getBalance() { | |
const { balance } = _state.get(this) | |
return balance | |
} | |
addToBalance(count) { | |
_addBalance.get(this)(count) | |
return this.getBalance() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment