This is the 11th day of my participation in the August Wenwen Challenge.More challenges in August

What is WeakSet?

WeakSet objects allow you to store weak-hold objects in a collection. Only reference types can be stored (an iterable: Including Array, Map, Set, String, TypedArray, the arguments object, etc.) as a parameter, and Set parameters can WeakSet structure is similar to the Set, and do not repeat the value of the collection, WeakSet with weak references: The reference of the object in the collection is weak reference, and WeakSet is not enumerable.

Why use WeakSet?

WeakSet is useful for storing DOM nodes without worrying about memory leaks when they are removed from documents. Here is another example of WeakSet.


const requests = new WeakSet(a);class ApiRequest {
  constructor() {
    requests.add(this);
  }
  makeRequest() {
    if(! request.has(this)) throw new Error("Invalid access");
    // do work}}Copy the code

For example, the ApiRequest class wants to verify the origin of this object, so it needs a collection to hold all objects built by the constructor. However, the ApiRequest class does not want to participate in the life cycle of the instance object. A memory leak occurs. If I write it in Set.

const requests = new Set(a);class ApiRequest {
  constructor() {
    requests.add(this);
  }
  makeRequest() {
    if(! request.has(this)) throw new Error("Invalid access");
    // do work
  }
  destory(){
    requests.delete(this)}}Copy the code

ApiRequest then has to participate in the management of the lifecycle while the consumer has to keep in mind the need for deStory.

use

WeakSet structure has the following three methods.

  • Add (Value) : Adds a new member to the WeakSet instance.
  • Delete (value) : Clears the specified member of a WeakSet instance.
  • Has (value) : Returns a Boolean value indicating whether a value is in a WeakSet instance.
var ws = new WeakSet(a);var foo = {};
var bar = {};

ws.add(foo);
ws.add(bar);

ws.has(foo);    // true
ws.has(bar);   // true

ws.delete(foo); // Remove foo from set and return false
ws.has(foo);    // false, the foo object has been deleted
ws.has(bar);    // true, bar still exists
Copy the code

foo ! = = the bar. Although they are similar objects, they are not the same object. * Therefore, they can all be added to the set.

Set 1. Members cannot be duplicated. 2. 3. It can traverse, including Add, delete,has weakSet 1. Members are all objects. 2. Members are weak references and can disappear at any time. Can be used to save DOM nodes, not easy to cause memory leakage 3. Cannot traverse, methods include add, delete,has Map 1. 2. Can traverse, many methods, can stem with a variety of data format conversion