Javascript - Collection WeakSet

Introduction

WeakSet object stores weakly held objects in a collection.

WeakSet doesn't prevent its elements from being garbage collected.

Values in a WeakMap must be unique object references.

A WeakSet is not iterable and does not have a size property.

A WeakSet supports only three methods:

  • add(value)
  • has(value)
  • delete(value)

Example

let ws = new WeakSet(); 
const obj = {}; 
const foo = {}; 

ws.add(window); 
ws.add(obj); 

ws.has(window); // true 
ws.has(foo);    // false, foo has not been added to the set 

ws.delete(window); // removes window from the set 
ws.has(window);    // false, window has been removed 

Use a WeakSet over a Set when you need Garbage Collection capabilities in the collection.

The following code shows how to prevent the usage of class methods on any object that was not created by the class constructor.

const fruits = new WeakSet(); 

class Fruit { 
  constructor() { 
    fruits.add(this); 
  } 

  getName() { 
    if (!fruits.has(this)) { 
      throw new TypeError("getName() called on an incompatible object!"); 
    } else { 
        // returns the name 
    } 
  } 
}