Skip to Content
Learning JavaScript Data Structures and Algorithms - Third Edition
book

Learning JavaScript Data Structures and Algorithms - Third Edition

by Loiane Avancini
April 2018
Beginner to intermediate content levelBeginner to intermediate
426 pages
10h 19m
English
Packt Publishing
Content preview from Learning JavaScript Data Structures and Algorithms - Third Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning JavaScript Data Structures and Algorithms

Learning JavaScript Data Structures and Algorithms

Loiane Avancini

Publisher Resources

ISBN: 9781788623872Supplemental Content