ES2015 classes with WeakMap

There is one datatype we can use to ensure that the property will be private in a class, and it is called WeakMap. We will explore the map data structure in detail in Chapter 8, Dictionaries and Hashes, but, for now, we need to know that a WeakMap can store a key value pair, where the key is an object and the value can be any datatype.

Let's see what the Stack class would look like if we used WeakMap to store the items attribute (array version):

const items = new WeakMap(); // {1} 
 
class Stack { 
  constructor () { 
    items.set(this, []); // {2} 
  } 
  push(element){ 
    const s = items.get(this); // {3} 
    s.push(element); 
  } 
  pop(){ 
    const s = items.get(this); 
    const r = s.pop(); 
    return r; 
  } 
  //other methods 
} 

The above code snippet ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.