- For this technique we set the key of the WeakMap to be the instance of the object the private properties belong to and we use a function (which we’ve called ) to create or return an object that all properties will be stored within.
- This technique has the benefit of not having the private properties shown on the instance when iterating over the properties or when doing but it relies on a WeakMap being available outside of the class itself which could be accessed and manipulated.
- All of the techniques shown so far still allow private properties to be accessed from outside the class, closures gives us a way of fixing that.
- Currently the proposal focuses on private class properties and not private functions or private members of object literals, these may come later.
So how can we go about protecting data that shouldn’t change during runtime? Let’s take a look at some options.
The first and most established method was to use a specific naming convention to indicate that a property should be treated as private. This usually had the property name prefixed with an underscore (e.g. ). This didn’t prevent the value from being access or modified but rather relied on an understanding between different developers that this value should be treated as off-limits.
For a slightly more restrictive option you can use…