Skip to content

Latest commit

 

History

History
42 lines (32 loc) · 998 Bytes

17-WeakSet.md

File metadata and controls

42 lines (32 loc) · 998 Bytes

Prev | Table of contents | Next

WeakSets

Like WeekMap but consists of values only (WeakSet = Set + Weakness - Iterable)

  1. Not iterable
  2. Values must be reference types
  3. Garbage collected
// has only .add, .has, .delete methods
const set = new WeakSet();

set.add({});
set.add(new Date());
set.add(1); // throws an exception

// or:
const newSet = new WeakSet([() => 'one', [], new Date()]);

Usage: (I've found only one example)

const fooInstances = new WeakSet();

class Foo
{
  constructor()
  {
    fooInstances.add(this);
  }

  method()
  {
    // check that prototype isn't faked
    if (!fooInstances.has(this)) { throw new Error('Foo.prototype.method called on incompatible object.'); }
  }
}

Prev | Table of contents | Next