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
- uniqueness
- Attribute name belongs to
Symbol
Type, 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
- Cannot operate with other types
Symbol
Value 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
- Type conversion
Symbol
Values 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
- Common unique value
Symbol
It’s any two of themSymbol
The values of the types are not equal, so we can set them all toSymbol
Type.Symbol
The type cannot use the new operator because the generatedSymbol
Is a primitive value, not an object.
- Private property
- Due to the
Symbol
Type as the property name, the property does not appear in thefor... in
,for... of
In 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 objectSymbol
The property name. So that we can putSymbol
Properties of a type are treated as private properties. - The new
API
.Reflect.ownKeys()
Method can return all types of key names, including regular key names andSymbol
The key name.
- 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 to
Symbol
Type.
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 calledSymbol
Instead, 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 samekey
The values created are equal. whileSymbol()
The value created is different each time, even thoughkey
The 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 registeredSymbol
Type the value of thekey
. unregisteredSymbol
Value, 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()
forSymbol
Value 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
- features
- Similar to an array, but with unique values and no duplicate values.
Set
The 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 inSet
In theNaN
andNaN
It’s the same thing.
- 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,
id
And so on.
Set
Instance properties and methodsSet
Instances 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
- with
Set
The difference between
WeakSet
A member of a can only be an object (null
Except), 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
WeakSet
Are weak references, which are not considered by the garbage collection mechanismWeakSet
A 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
.
- 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
WeakSet
There is nosize
Property, there is no way to traverse its members.
Map
- Due to the traditional
Object
Object can only use strings as keys, so newMap
Structures 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
- methods
- Compared with the
Set
Operation method of,Map
There is noadd
Method, addedget
Methods andset
Methods. 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
- conversion
(1)Map
And an array- It was mentioned in the second bullet
Map
And 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)
Map
And the objectMap
Keys 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 toMap
Can 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
- It was mentioned in the second bullet
- application
- This can be used when the stored data is key-value pairs and the type of the key name may be multiple
Map
Structure.withjava
In theMap
The structure is different.
WeakMap
- with
Map
The difference betweenWeakMap
Only objects are accepted as key names (null
Values 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
WeakMap
Is 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.e
keys()
,values()
andentries()
Method), neithersize
Properties. - Cannot be cleared, that is, not supported
clear
Methods.WeakMap
There are only four methods available:get()
,set()
,has()
,delete()
.
- application
(1)DOM
Node as the key namedocument.getElementById('logo')
Is aDOM
Node whenever occursclick
Event, just update the status. We put this state as the keyWeakMap
In, the corresponding key name is the node object. Once theDOM
When 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