Page 183 - JavaScript
P. 183
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 gardner';
this.doMission = () => {
figureWhatToDo(topSecret.get(this)); // we have access to topSecret
};
}
}
Because the const topSecret is defined inside our module closure, and since we didn't bind it to
our instance properties, this approach is totally private, and we can't reach the agent topSecret.
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 gardner';
this.doMission = () => {
figureWhatToDo(topSecret); // we have access to topSecret
};
}
}
In this example as well the data is 100% private and can't be reached outside the class, so our
agent is safe.
Using naming conventions
We will decide that any property who is private will be prefixed with _.
Note that for this approach the data isn't really private.
export class SecretAgent{
constructor(secret){
this._topSecret = secret; // it private by convention
this.coverStory = 'just a simple gardner';
this.doMission = () => {
figureWhatToDo(this_topSecret);
};
}
}
Class Name binding
https://riptutorial.com/ 140

