Encapsulate Truly Private Variables in a Closure

Marius Schulz
InstructorMarius Schulz
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

Closures are an alternative to truly private class fields. If you need to encapsulate a private variable so that it can only be accessed in a controlled way, you can use a closure. This technique is particularly useful when your code has to run in older JavaScript environments that don't yet support truly private class fields or the ES2015 WeakMap data structure.

Instructor: [0:01] If you do need true privacy, and you have to support an older JavaScript version such as ES5, instead of using a class, you can use a closure. In our example, this could have looked as follows.

[0:13] We could have written a function called createCounter() and within that function we could have defined a local variable called value. From within that function, we would return an object with an increment method which would increment our value variable and the getter we defined before which would simply return the value of the variable. Lastly, instead of calling newCounter, we would now call createCounter.

[0:40] Note that this approach is still giving us the same benefits of true privacy. The local variable value is inaccessible from outside of the createCounter function. The only way we can modify this variable is using the increment method, and we can only do so in a controlled way.

[0:57] Let's run one final check to make sure that this is working and that's looking all right.

egghead
egghead
~ just now

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today