Last active
September 5, 2015 07:54
-
-
Save tcw165/87c5bcfee9760666a774 to your computer and use it in GitHub Desktop.
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
/** | |
* How to declare a real private members in a JavaScript class? | |
* | |
* Prerequisities | |
* -------------- | |
* 1. This is a node module, as it's wrapped in a closure (Module Pattern). | |
* e.g. var XXX = (function() { ... })(); | |
* 2. Need ES6 support. | |
* | |
* Solution | |
* -------- | |
* Because Keys of WeakMaps are of the type Object only. Primitive data types as | |
* keys are not allowed (e.g. a Symbol can't be a WeakMap key). We can use it to | |
* store private members. | |
*/ | |
let pv = new WeakMap(); | |
export default class TheClass { | |
constructor() { | |
// Private members ///////////////////////////////////////////////////////// | |
pv.set(this, { | |
props1: 0, | |
props2: '456', | |
props3: '789' | |
}); | |
// Public members ////////////////////////////////////////////////////////// | |
this.pub1 = 123; | |
this.pub2 = 456; | |
} | |
/** | |
* Public function 1. | |
*/ | |
publicFn1() { | |
// Alter the private members by increasing it by one. | |
++pv.get(this).props1; | |
console.log(pv.get(this).props1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment