All variables declared inside the function are private to it. They can be accessed only from the function itself and through the closure of the nested ones.
Since in the normal implementation of a class, functions are placed in the prototype and exist in a single copy, they cannot gain access to instance variables through a closure (there is one function, but there are many instances — the function cannot “choose” the closure at the time of the call).
The following solutions are possible:
Classic underscore in name
If the name begins with an underscore, then by oral agreement it is considered that it should not be touched. Naturally, at the code level, this does not provide any privacy.
Discard methods in prototype and place methods in instances
Privacy is thus ensured, however, a large number of functions of the same type are created, differing only in closures.
This approach is considered to be irrational, but it is quite common in the implementation of various services, which are essentially singletones.
The Symbol type is a special type of key. You can access the field value only by having the character itself, through which this value was recorded.
This is quite similar to privacy, but does not provide full protection against access, since all the character keys for an object can be obtained through Object.getOwnPropertySymbols .
Symbol is ES6. Polyphiles for it generate a regular field with a sufficiently random key to eliminate intersections with other fields.
A single closure may be common to the constructor and all prototype methods. But instances should be somehow distinguished. If we put into this closure something where the instance is the key, and the value is the entire set of private fields, then we get complete real privacy.
However, there is a problem. If we keep something like an array, it will keep all our objects from garbage collection, that is, we get a memory leak. This problem is solved by the WeakMap introduced in ES6, which allows the garbage collector to destroy objects that are its keys.
Polyphil for WeakMap is to put a certain field in the object itself and save the name of this field in the map. In fact, we slide to the previous method.