WeakMap Private Data in JavaScript
Level 5347 keystrokes
WeakMap can store private data associated with objects without preventing garbage collection.
JavaScript code
// WeakMap stores private data for instances1const privateData = new WeakMap();// Define Person class2class Person { // Constructor takes name and age3 constructor(name, age) { // Store private data using instance as key4 privateData.set(this, { name, age });5 } // Getter method for name6 getName() { // Retrieve name from private data7 return privateData.get(this).name;8 } // Getter method for age9 getAge() { // Retrieve age from private data10 return privateData.get(this).age;11 }12}// Create a Person instance13const person = new Person("Alice", 30);// Access name through method14console.log(person.getName());// Access age through method15console.log(person.getAge());// Object.keys returns []: name and age are not properties of the instance16console.log(Object.keys(person));Output
Alice 30 []
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
(× 14)× 14.× 11;× 8{× 5}× 5,× 4"× 2=× 2