Last active
March 12, 2019 04:32
-
-
Save CodeOtter/4b2e048d7f70590fb2c2dcd837987f97 to your computer and use it in GitHub Desktop.
How to sanely make private variables in modern JavaScript
This file contains 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
// Using the WeakMap approach, the variables are kept outside of public access and when the instance of | |
// SomeClass is no longer referenced, all of its variables will be GCed as well | |
const instances = new WeakMap() | |
class SomeClass { | |
constructor (privateVar1, privateVar2, privateVar3) { | |
instances.set(this, { | |
privateVar1, | |
privateVar2, | |
privateVar3 | |
}) | |
} | |
someMethod () { | |
const { privateVar1, privateVar2, privateVar3 } = instances.get(this) | |
// Do stuff with the private variables, make sure you instances.set any changes you need to make | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment