Skip to content

Instantly share code, notes, and snippets.

@nairihar
Created April 28, 2018 12:26
Show Gist options
  • Save nairihar/d0acbb4211f611a5bcc8cc376db1ac5a to your computer and use it in GitHub Desktop.
Save nairihar/d0acbb4211f611a5bcc8cc376db1ac5a to your computer and use it in GitHub Desktop.
Privates in JavaScript WeakMap, medium, using WeakMap, es6
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