Managing Private Data with Classes

suggest change

Classes now have # private fields, which other code cannot read. The four older approaches below are still common. figureWhatToDo in the samples is a stand-in. It is not defined here.

Using Symbols

Symbols have been a primitive type since ES2015. See MDN.

A symbol is a unique and immutable data type that may be used as an identifier for object properties.

When using symbol as a property key, it is not enumerable.

A symbol key is not listed by for...in or Object.keys.

Thus we can use symbols to store private data.

const topSecret = Symbol('topSecret'); // our private key; will only be accessible on the scope of the module file
export class SecretAgent{
    constructor(secret){
        this[topSecret] = secret; // we have access to the symbol key (closure)
        this.coverStory = 'just a simple gardener';
        this.doMission = () => {
            figureWhatToDo(this[topSecret]);
        };
    }
}

Because symbols are unique, we must have reference to the original symbol to access the private property.

import {SecretAgent} from 'SecretAgent.js'
const agent = new SecretAgent('steal all the ice cream');
// ok lets try to get the secret out of him!
Object.keys(agent); // ['coverStory', 'doMission']; the symbol key is omitted
agent[Symbol('topSecret')]; // undefined, as we said, symbols are always unique, so only the original symbol will help us to get the data.

But it’s not 100% private; let’s break that agent down! We can use the Object.getOwnPropertySymbols method to get the object symbols.

const secretKeys = Object.getOwnPropertySymbols(agent);
agent[secretKeys[0]] // 'steal all the ice cream' , we got the secret.

Using WeakMaps

WeakMap has been standard since ES2015. See MDN.

The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. The keys must be objects and the values can be arbitrary values.

Another important feature of WeakMap is, as defined on MDN.

The key in a WeakMap is held weakly. What this means is that, if there are no other strong references to the key, the entire entry will be removed from the WeakMap by the garbage collector.

The idea is to use the WeakMap, as a static map for the whole class, to hold each instance as key and keep the private data as a value for that instance key.

Thus only inside the class will we have access to the WeakMap collection.

Let’s give our agent a try, with WeakMap:

const topSecret = new WeakMap(); // will hold all private data of all instances.
export class SecretAgent{
    constructor(secret){
        topSecret.set(this,secret); // we use this, as the key, to set it on our instance private data
        this.coverStory = 'just a simple gardener';
        this.doMission = () => {
            figureWhatToDo(topSecret.get(this));
        };
    }
}

Code that cannot see the module-scoped topSecret map cannot read the secret through the instance. This is privacy by closure, not a # field. Exporting the map would give it away.

Define all methods inside the constructor

The idea here is simply to define all our methods and members inside the constructor and use the closure to access private members without assigning them to this.

export class SecretAgent{
     constructor(secret){
         const topSecret = secret;
         this.coverStory = 'just a simple gardener';
         this.doMission = () => {
             figureWhatToDo(topSecret); // we have access to topSecret
         };
     }
 }

The secret is closed over, so other code cannot read that binding. Each instance gets its own doMission function, which costs more memory than a method on the prototype.

Using naming conventions

A leading underscore is only a convention. The property is still a normal public property.

export class SecretAgent{
    constructor(secret){
        this._topSecret = secret; // it private by convention
        this.coverStory = 'just a simple gardener';
        this.doMission = () => {
            figureWhatToDo(this._topSecret);
        };
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents