Written in the beginning

  • Tomorrow is the Dragon Boat Festival, I wish you a healthy Dragon Boat Festival in advance.
  • ES6 common but ignored methods series of articles, sorting out the author thinks that some daily development may use some methods, use skills and some application scenarios, details please see related content links, welcome to supplement exchange.

Related articles

  • Common but overlooked methods for ES6 (Destruct assignments and values first)
  • ES6 Common but ignored methods (second bullet functions, arrays, and objects)
  • ES6 commonly used but overlooked methods (fourth bullet Proxy and Reflect)
  • ES6 common but ignored methods (# 5 Promise and Iterator)
  • Common but ignored methods for ES6 (Generator 6)
  • ES6 Common but ignored methods (async)
  • ES6 Common but ignored methods (eighth bullet Class)
  • ES6 common but ignored methods (Module 9)
  • Common but ignored methods of ES6 (Development specification of the Tenth Bullet Project)
  • ES6 common but ignored method (eleventh bullet Decorator)
  • Common but overlooked approaches to ES6 (End game – Latest Proposal)

Symbol

  • ES6-Symbol

features

  1. uniqueness
  • Attribute name belongs toSymbolType, are unique and are guaranteed not to conflict with other property names. Even two statements that are exactly the same are not equal.
// let s1 = Symbol(); let s2 = Symbol(); S1 === s2 // false // let s1 = ('foo'); let s2 = Symbol('foo'); s1 === s2 // falseCopy the code
  1. Cannot operate with other types
  • SymbolValue cannot be evaluated with other types of values and an error is reported.
let sym = Symbol('My symbol');
"your symbol is " + sym
// TypeError: can't convert symbol to string
`your symbol is ${sym}`
// TypeError: can't convert symbol to string
Copy the code
  1. Type conversion
  • SymbolValues can be explicitly converted to strings and Booleans, but not numeric values.
let sym = Symbol('My symbol'); String(sym) // 'Symbol(My symbol)' sym.toString() // 'Symbol(My symbol)' let sym = Symbol(); Boolean(sym) // true ! sym // false Number(sym) // TypeError sym + 2 // TypeErrorCopy the code

The application of Symbol

  1. Common unique value
  • SymbolIt’s any two of themSymbolThe values of the types are not equal, so we can set them all toSymbolType.SymbolThe type cannot use the new operator because the generatedSymbolIs a primitive value, not an object.
  1. Private property
  • Due to theSymbolType as the property name, the property does not appear in thefor... in,for... ofIn the loop, it won’t beObject.keys(),Object.getOwnPropertyNames(),JSON.stringify()To return. Need to pass throughObject.getOwnPropertySymbols()Method to get all of a specified objectSymbolThe property name. So that we can putSymbolProperties of a type are treated as private properties.
  • The newAPI.Reflect.ownKeys()Method can return all types of key names, including regular key names andSymbolThe key name.
  1. Erase magic string
  • A magic string is a specific string or number that occurs multiple times in the code and is strongly coupled to the code. We can set the corresponding string or value toSymbolType.
const name = { first: Symbol('detanx') } function getName(firstName) { switch (firstName) { case name.first: // Magic string... } } getName(name.first); // Magic stringCopy the code

Symbol. The for () and Symbol. KeyFor ()

  • Symbol.for()It doesn’t return a new one every time it’s calledSymbolInstead, the given key is checked to see if it already exists, and a new value is created if it does not. That is if you pass in the samekeyThe values created are equal. whileSymbol()The value created is different each time, even thoughkeyThe same.
let s1 = Symbol.for('detanx');
let s2 = Symbol.for('detanx');
s1 === s2 // true

let s1 = Symbol('detanx');
let s2 = Symbol('detanx');
s1 === s2 // false
Copy the code
  • Symbol.keyFor()Method returns a registeredSymbolType the value of thekey. unregisteredSymbolValue, returnundefined.
let s1 = Symbol.for("detanx");
Symbol.keyFor(s1) // "detanx"

let s2 = Symbol("detanx");
Symbol.keyFor(s2) // undefined
Copy the code
  • Symbol()The notation has no registration mechanism, so each call returns a different value.
  • Symbol.for()forSymbolValue is registered as the name of the global environment, whether or not it is running in the global environment.

The built-in Symbol value

  • The built-in Symbol value want to know you can jump over to see.

Set and Map data structures

  • Es6-set and Map data structures

Set

  1. features
    • Similar to an array, but with unique values and no duplicate values.
    • SetThe function can take an array (or have one可迭代Other data structures of the interface) as parameters used for initialization.
    • Whether the two internal data are the same basic sum= = =Similar, the difference is inSetIn theNaNandNaNIt’s the same thing.
  2. application
    • Array or string deduplication.
    [...new Set([1, 1, 2, 3])] // [1, 2, 3]
    
    [...new Set('ababbc')].join('') // "abc"
    Copy the code
    • Some data that requires uniqueness, such as user names,idAnd so on.
  3. SetInstance properties and methods
    • SetInstances of a structure have the following properties.
    Set. The prototype. The constructor: constructor, the default is Set function. Set.prototype.size: Returns the total number of members of a Set instance.Copy the code
    • Operation method (for manipulating data)
    Set.prototype.add(value) : Adds a value and returns the Set structure itself. Set.prototype.delete(value) : Deletes a value and returns a Boolean value indicating whether the deletion was successful. Set.prototype.has(value) : Returns a Boolean value indicating whether the value is a member of Set. Set.prototype.clear() : Clears all members with no return value.Copy the code
    • Traversal method (for traversing members)
    Set.prototype.keys() : set.prototype.values () : set.prototype.entries () : set.prototype.foreach () : set.prototype.foreach () : set.prototype.keys () : set.prototype.values () : set.prototype.entries () : set.prototype.foreach () : Use the callback function to iterate over each memberCopy the code

WeakSet

  1. withSetThe difference between
  • WeakSetA member of a can only be an object (nullExcept), and cannot be any other type of value.
const ws = new WeakSet();
ws.add(1) // TypeError: Invalid value used in weak set
ws.add(Symbol())  // TypeError: invalid value used in weak set
ws.add(null)  // TypeError: invalid value used in weak set
Copy the code
  • WeakSetAre weak references, which are not considered by the garbage collection mechanismWeakSetA reference to an object, that is, if no other object references the object, the garbage collection mechanism automatically reclaims the memory occupied by the object, regardless of the object’s existenceWeakSet.
  1. Methods.
Weakset.prototype. add(value) : Adds a new member to the WeakSet instance. Weakset.prototype. delete(value) : Clears the specified member of a WeakSet instance. Weakset.prototype. has(value) : Returns a Boolean value indicating whether a value is in a WeakSet instance.Copy the code
  • WeakSetThere is nosizeProperty, there is no way to traverse its members.

Map

  • Due to the traditionalObjectObject can only use strings as keys, so newMapStructures can treat all types of values, including objects, as keys.
const m = new Map();
const o = {p: 'Hello World'};

m.set(o, 'content')
m.get(o) // "content"
Copy the code
  1. methods
  • Compared with theSetOperation method of,MapThere is noaddMethod, addedgetMethods andsetMethods. The traversal method is basically the same.
Map.prototype.get(key) // Return undefined if key is not found. Map.prototype.has(key) // Returns a Boolean value indicating whether a key is in the current Map object.Copy the code
  1. conversion

    (1) MapAnd an array
    • It was mentioned in the second bulletMapAnd arrays, and it’s very convenient to rotate between them.
    // Map converted to array const myMap = new Map().set(true, 7).set({foo: 3}, [' ABC ']); MyMap [...] / [[true, 7], [3} {foo:, [' ABC ']]] / / array into the Map. new Map([ [true, 7], [{foo: 3}, ['abc']] ]) // Map { // true => 7, // Object {foo: 3} => ['abc'] // }Copy the code

    (2) MapAnd the object

    • MapKeys are strings that can be converted to objects losslessly. If there is a non-string key name, it is converted to a string and used as the object’s key name. Object toMapCan be achieved byObject.entries().
    // Map => Object
    function strMapToObj(strMap) {
      let obj = Object.create(null);
      for (let [k,v] of strMap) {
        obj[k] = v;
      }
      return obj;
    }
    
    const myMap = new Map()
      .set('yes', true)
      .set('no', false);
    strMapToObj(myMap)
    // { yes: true, no: false }
    
    // Object => Map
    // let obj = {"a":1, "b":2};
    let map = new Map(Object.entries(obj));
    Copy the code
  2. application
  • This can be used when the stored data is key-value pairs and the type of the key name may be multipleMapStructure.withjavaIn theMapThe structure is different.

WeakMap

  1. withMapThe difference between
    • WeakMapOnly objects are accepted as key names (nullValues of other types are not accepted as key names.
    const map = new WeakMap();
    map.set(1, 2) // TypeError: 1 is not an object!
    map.set(Symbol(), 2) // TypeError: Invalid value used as weak map key
    map.set(null, 2) // TypeError: Invalid value used as weak map key
    map.set(new Number(1), 2) // WeakMap {Number => 2}
    Copy the code
    • WeakMapIs not counted in the garbage collection mechanism. Once the objects are no longer needed, we must manually remove the reference, otherwise the garbage collection mechanism will not free up the memory.
    const e1 = document.getElementById('foo'); const e2 = document.getElementById('bar'); Const arr = [[e1, 'foo '], [e2, 'bar '],]; Arr [0] = null; arr [0] = null; arr [1] = null;Copy the code
    • WeakMap weakly references only the key name, not the key value. Key values are still normal references.
    • No traversal operation (i.ekeys(),values()andentries()Method), neithersizeProperties.
    • Cannot be cleared, that is, not supportedclearMethods.WeakMapThere are only four methods available:get(),set(),has(),delete().
  2. application

    (1) DOMNode as the key name
    • document.getElementById('logo')Is aDOMNode whenever occursclickEvent, just update the status. We put this state as the keyWeakMapIn, the corresponding key name is the node object. Once theDOMWhen the node is deleted, the status disappears automatically, and there is no risk of memory leakage.
    let myWeakmap = new WeakMap();
    
    myWeakmap.set(
      document.getElementById('logo'),
      {timesClicked: 0})
    ;
    
    document.getElementById('logo').addEventListener('click', function() {
      let logoData = myWeakmap.get(document.getElementById('logo'));
      logoData.timesClicked++;
    }, false);
    Copy the code

    (2) Deploy private properties

    • Internal properties are weak references to the instance, so if the instance is deleted, they disappear without causing a memory leak.
    const _counter = new WeakMap();
    const _action = new WeakMap();
    
    class Countdown {
      constructor(counter, action) {
        _counter.set(this, counter);
        _action.set(this, action);
      }
      dec() {
        let counter = _counter.get(this);
        if (counter < 1) return;
        counter--;
        _counter.set(this, counter);
        if (counter === 0) {
          _action.get(this)();
        }
      }
    }
    
    const c = new Countdown(2, () => console.log('DONE'));
    
    c.dec()
    c.dec()
    // DONE
    Copy the code