Skip to content

Instantly share code, notes, and snippets.

@CodeOtter
Last active March 12, 2019 04:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CodeOtter/4b2e048d7f70590fb2c2dcd837987f97 to your computer and use it in GitHub Desktop.
Save CodeOtter/4b2e048d7f70590fb2c2dcd837987f97 to your computer and use it in GitHub Desktop.
How to sanely make private variables in modern JavaScript
// 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