Encapsulate Truly Private Variables in a Closure

Marius Schulz
InstructorMarius Schulz

Share this video with your friends

Send Tweet
Published a year ago
Updated a year 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.