Special statement: The original is not easy, shall not be reproduced without authorization or plagiarism, if you need to reprint can contact the author authorization

preface

The third time to read ruan Yifeng teacher “ES6 standard introduction”, before the reading is not careful, many places are a glance ten lines. In my recent reading, I have been reading word by word and found many knowledge points that I didn’t notice before. I am writing this article for the convenience of memorizing and previewing all ES6 features.

The ES6 Standard Introduction mentioned below uses the name ES6 instead, and the latest version of ES6 is up to the current ES2020Copy the code

The knowledge points in this paper are completely referenced or excerpted from the sentences in ES6. In order to facilitate understanding and memory, some sentences are escaped with the same meaning, and the knowledge points are classified and divided at the same time. In order to let you concentrate on remembering these features, there is no nonsense or digression in the full text. All modules are written in the form of notes. If you are not used to reading, it is recommended to study by referring to the content of ES6.

The notes collected in this article are the highlights of the book, covering all the features of the ES6 system, and are very convenient for you to re-understand all the features of ES6. Half an hour of reading will give you a comprehensive understanding of ES6, which can be regarded as a small dictionary of ES6 features. After collecting, you can refer to it at any time. Even if you can’t finish reading, pull to the end of this article, there is a big Easter egg, hee hee!

correction

ES6 is ECMA’s sixth standard version for JavaScript. For a history, see the section ES6- Introduction to ECMAScript6.

In the end, the standards committee decided that the standard would be released in June of each year as the official version of that year, and that changes would be made from that version until June of the following year, when the draft would naturally become the New Year’s version, so that the previous version number would not be needed, and only the year would be used. ECMAscript 2015 was the first release of ES6 in June 2015. ECMAscript 2016 is the second version of ES6, and ECMAscript 2017 is the third version of ES6. ES6 is both a historical term and a general term, referring to the next generation of JavaScript standards after version 5.1, which currently covers ES2015, ES2016, ES2017, ES2018, ES2019, ES2020.

So ES7(essentially ES2016), ES8(essentially ES2017), ES9(essentially ES2018), ES10(essentially ES2019), ES11(essentially ES2020) mentioned in some articles are essentially non-standard concepts. From ES1 to ES6, each standard took several years or even more than a decade to develop, you have an ES6 to ES7, ES7 to ES8, in a year, by this definition, that is not very soon ES20. To put the concept in perspective, ES6 currently covers ES2015, ES2016, ES2017, ES2018, ES2019, ES2020.

In addition, the content of ES6 update is mainly divided into the following points

  • Expressions: declare and deconstruct assignments
  • Built-in objects: String extension, numeric extension, object extension, array extension, function extension, regular extension, Symbol, Set, Map, Proxy, Reflect
  • Statements and operations: Class, Module, Iterator
  • Asynchronous programming: Promise, Generator, and Async

ES2015

The statement

  • Const command: Declare constants
  • The let commandDeclare variables

role

  • scope
    • Global scope
    • Function scope:function() {}
    • Block-level scope:{}
  • scope
    • Var commandExecute in global code
    • Const commandandThe let commandCan only be executed in a code block
  • Assignment using
    • Const commandConstants must be assigned immediately after they are declared
    • The let commandVariables can be assigned immediately after they are declared or when they are used
  • Declaration method:var,const,let,function,class,import

The difficult

  • Repeated declarations are not allowed
  • Error:Const commandandThe let commandThere is no variable promotion
  • Temporary dead zones: Used within code blocksConst commandandThe let commandA variable is not available until it is declared

Deconstruction assignment

  • String deconstruction:const [a, b, c, d, e] = "hello"
  • Numerical deconstruction:const { toString: s } = 123
  • Boolean deconstruction:const { toString: b } = true
  • Object to deconstruct
    • Form:const { x, y } = { x: 1, y: 2 }
    • The default:const { x, y = 2 } = { x: 1 }
    • Name:const { x, y: z } = { x: 1, y: 2 }
  • An array of deconstruction
    • Rules: Data structures haveThe Iterator interfaceDestructible assignments can take the form of arrays
    • Form:const [x, y] = [1, 2]
    • The default:const [x, y = 2] = [1]
  • Function parameter decomposition
    • Array deconstruction:function Func([x = 0, y = 1]) {}
    • Object deconstruction:function Func({ x = 0, y = 1 } = {}) {}

Application scenarios

  • Exchange variable values:[x, y] = [y, x]
  • Returns multiple values to a function:const [x, y, z] = Func()
  • Define function parameters:Func([1, 2])
  • Extract JSON data:const { name, version } = packageJson
  • Define default values for function arguments:function Func({ x = 1, y = 2 } = {}) {}
  • Traversing the Map structure:for (let [k, v] of Map) {}
  • The input module specifies the properties and methods:const { readFile, writeFile } = require("fs")

The difficult

  • Matching patterns: As long as the patterns on both sides of the equals sign are the same, the variables on the left are assigned their corresponding values
  • Destruct assignment rule: As long as the value to the right of the equal sign is not an object or an array, convert it to an object first
  • Destruct default value Valid condition: the value of the property must be equal toundefined
  • Deconstruction follows a matching pattern
  • The value of the variable when the deconstruction fails is equal toundefined
  • undefinedandnullCannot be converted to an object and therefore cannot be deconstructed

String extension

  • Unicode representation:Curly braces containRepresents Unicode characters (\u{0xXX}or\u{0XXX})
  • String traversal: byfor-ofTraversal string
  • String template: an enhanced string with single or multiple lines and insertable variables
  • The label template: A special call to a function argument
  • String.raw(): Returns the result of replacing all the variables in the string and escaping the slash
  • String.fromCodePoint(): The character corresponding to the return code point
  • codePointAt(): returns the corresponding character code point (String.fromCodePoint()The inverse operation of)
  • normalize(): unify the different expressions of characters into the same form and returnA new string(Unicode normalization)
  • repeat(): repeats the string n times and returnsA new string
  • matchAll(): returns all matches of the regular expression in the string
  • includes(): Indicates whether a specified string exists
  • startsWith(): Whether a string header exists to specify a string
  • endsWith(): Specifies whether there is a string tail

The difficult

  • All of the above extension methods can be applied to cause4 bytes for storagetheUnicode characterson

Numerical extension

  • Binary notation:It starts with 0B or 0BRepresent binary (0bXXor0BXX)
  • Octal notation:Start with 0o or 0oRepresent binary (0oXXor0OXX)
  • Number.EPSILON: Minimum numerical precision
  • Number.MIN_SAFE_INTEGER: Minimum safe value (- 2 ^ 53)
  • Number.MAX_SAFE_INTEGER: Maximum safety value (2 ^ 53)
  • Number.parseInt(): Returns the integer portion of the converted value
  • Number.parseFloat(): Returns the floating point portion of the converted value
  • Number.isFinite(): Indicates whether the value is a finite value
  • Number.isNaN(): Indicates whether the value is NaN
  • Number.isInteger(): Whether the value is an integer
  • Number.isSafeInteger(): Whether the value is within the safe range
  • Math.trunc(): Returns the integer part of the value
  • Math.sign(): returns a numeric type (A positive number 1,A negative number - 1,Zero zero)
  • Math.cbrt(): returns a numeric cube root
  • Math.clz32(): Returns a 32-bit unsigned integer of a value
  • Math.imul(): Returns the multiplication of two values
  • Math.fround(): Returns a 32-bit single-precision floating point form of a value
  • Math.hypot(): Returns the square root of all numeric sums of squares
  • Math.expm1()Returns thee^n - 1
  • Math.log1p()Returns the1 + nThe natural log of (Math.log(1 + n))
  • Math.log10(): returns logarithm base 10 of n
  • Math.log2(): returns logarithm base 2 of n
  • Math.sinh()Returns the hyperbolic sine of n
  • Math.cosh(): returns the hyperbolic cosine of n
  • Math.tanh(): returns the hyperbolic tangent of n
  • Math.asinh()Returns the inverse hyperbolic sine of n
  • Math.acosh()Returns the inverse hyperbolic cosine of n
  • Math.atanh(): returns the inverse hyperbolic tangent of n

Object extension

  • Simple notation: Writes variables and functions directly as properties and methods of objects ({ prop, method() {} })
  • Attribute name expression: is used to define an object[]Define key ([prop]Cannot be used at the same time as above)
  • Method name attribute: Returns the name of the method function
    • Getters and setters:Get/set the function nameThe description object of the property is ingetandsetOn)
    • Function returned by bind:Bound function name
    • The Function constructor returns an instance of the Function:anonymous
  • The enumerability and traversal of properties: Describing an objectenumerable
  • The super keyword: refers to the prototype object of the current object (used only in shorthand methods of objectsmethod() {})
  • Object.is(): Compares two values for equality
  • Object.assign(): Merges the object (shallow copy) and returns the original object
  • Object.getPrototypeOf(): returns the prototype object of the object
  • Object.setPrototypeOf(): Sets the prototype object of the object
  • __proto__: Returns or sets the prototype object of the object

Attribute traversal

  • Description:Their own,inheritable,Can be enumerated,The enumeration,Symbol
  • traverse
    • for-in: Traverses the objectItself can inherit and enumerateattribute
    • Object.keys(): returns an objectSelf enumerableAn array of property keys
    • Object.getOwnPropertyNames(): returns an objectIts not the SymbolAn array of property keys
    • Object.getOwnPropertySymbols(): returns an objectIts SymbolAn array of property keys
    • Reflect.ownKeys(): returns an objectIts allAn array of property keys
  • The rules
    • The first step is to iterate through all the numeric keys in ascending order
    • The next step is to iterate over all the string keys in ascending order by the time they were added
    • Finally, all Symbol keys are traversed in ascending order by time of addition

Array extension

  • Extension operator (…): converts an array to a comma-separated sequence of arguments ([...arr], which is equivalent toRest/spread parametersThe inverse of
  • Array.from(): The transformation hasThe Iterator interfaceThe data structure is a true array and returns the new array
    • Array-like objects:An object that contains length,The Arguments object,The NodeList object
    • Traversable objects:String,The Set structure,Structure of the Map,The Generator function
  • Array.of(): converts a set of values to a true array and returns the new array
  • copyWithin(): copies members from a specified location to another location, returning the original array
  • find(): Returns the first eligible member
  • findIndex(): returns the first member index that meets the criteria
  • fill(): Populates the entire array with the specified value and returns the original array
  • keys(): returns an object traversed by an index
  • values(): Returns an object that traverses the property value
  • entries(): Returns an object with index and property values as iterators
  • An array of space: ES6 explicitly converts array vacancies toundefined(It is recommended to avoid empty space because of different processing rules)

Extended application

  • Clone an array:const arr = [...arr1]
  • Merge arrays:const arr = [...arr1, ...arr2]
  • Splicing arrays:arr.push(... arr1)
  • Instead of the apply:Math.max.apply(null, [x, y])= >Math.max(... [x, y])
  • Convert a string to an array:[..."hello"]
  • Convert array-like objects to arrays:[...Arguments, ...NodeList]
  • Convert a traversable object to an array:[...String, ...Set, ...Map, ...Generator]
  • Combined with array destruct assignment:const [x, ...rest/spread] = [1, 2, 3]
  • Calculate Unicode character length:Array.from("hello").length= >[..."hello"].length

The difficult

  • usekeys(),values(),entries()The returned iterator object is availablefor-ofAutomatic traversal ornext()Manual traverse

Function extension

  • Parameter Default values: Specifies default values for function arguments
    • Form:function Func(x = 1, y = 2) {}
    • Parameter assignment: lazy evaluation (evaluated after the function is called)
    • Parameter position: tail parameter
    • Parameter scope: Function scope
    • Declaration mode: The default declaration cannot be usedconstorletOnce again
    • Length: Returns the number of parameters without a default value
    • Combined with the destruct assignment default:function Func({ x = 1, y = 2 } = {}) {}
    • application
      • Specifies that an argument must not be omitted, otherwise an error is thrown:function Func(x = throwMissing()) {}
      • Set the parameter default toundefined, indicating that this parameter can be omitted:Func(undefined, 1)
  • Rest/spread parameter (…).: Returns extra arguments to the function
    • Form: exists as an array, after which there can be no other arguments
    • Function: replaceThe Arguments object
    • Length: Returns the number of parameters with no default value but not includedRest/spread parameters
  • Strict mode: Run JS under strict conditions
    • Application: As long as function parameters use default values, destruct assignments, and extend operators, then functions cannot be explicitly set to strict mode internally
  • The name attribute: Returns the name of the function
    • Assign an anonymous function to a variable:An empty string(ES5),The variable name(ES6)
    • Assign a named function to a variable:The function name(ES5 and ES6)
    • Function returned by bind:Bound function name(ES5 and ES6)
    • The Function constructor returns an instance of the Function:anonymous(ES5 and ES6)
  • Arrow function (=>): is short for function
    • No arguments:() = > {}
    • Single parameter:x => {}
    • Multiple parameters:(x, y) => {}
    • Destruct parameters:({x, y}) => {}
    • Nested use: Deploy the pipeline mechanism
    • This refers to immobilization
      • It’s not because there’s an internal bindingthisInstead of having its own mechanism at allthis, resulting in internalthisIt’s the outer code blockthis
      • Because there is nothis, and therefore cannot be used as a constructor
  • Tail call optimization: Only the call frames of inner functions are retained
    • The tail call
      • Definition: The last step in a function is to call another function
      • Form:function f(x) { return g(x); }
    • Tail recursion
      • Definition: function tail calls itself
      • Function: as long as the use of tail recursion will not occur stack overflow, relatively save memory
      • Implementation: rewrites all internal variables used as function arguments and uses parameter defaults

Error of arrow function

  • Functional in vivothisisThe object where the definition is locatedRather thanThe object in which it is used
  • Can let athisPoints to immobilization, a feature that is useful for encapsulating callback functions
  • Not as aThe constructor, so the arrow function is not availableThe new command
  • Do not useYield command, so the arrow function cannot be usedThe Generator function
  • Do not useThe Arguments objectThis object does not exist in the function body (available)Rest/spread parametersInstead of)
  • An object must be returned in parentheses

Regular extension

  • Change the RegExp constructor parameters: Allows the first parameter to beRegular object, tail parameter isRegular modifier(The returned regular expression ignores the qualifier of the original regular expression.)
  • Regular method call changes: of string objectsmatch(),replace(),search(),split()Internal calls become callsRegExpInstance correspondingThe RegExp. Prototype [Symbol. Methods]
  • U modifier: Unicode schema modifier that handles properly greater than\uFFFFtheUnicode characters
    • Some characters(.).
    • Unicode representation
    • quantifiers
    • Predefined pattern
    • The I modifier
    • escape
  • Y modifier: adhesion modifier that ensures that matches must start with the first remaining positionG modifierSimilar effect)
  • unicode: Whether to setU modifier
  • sticky: Whether to setY modifier
  • flags: Returns the modifier of a regular expression

The difficult

  • Y modifierImplied header matching flag^
  • Just oneY modifierrightmatch()Only the first match must be returnedG modifierAll matches are returned in combination

Symbol

  • Definition: unique value
  • Statement:const set = Symbol(str)
  • Input parameter: string (optional)
  • methods
    • Symbol(): Creates an object described by parametersSymbol value(Not registered in the global environment)
    • Symbol.for(): Creates an object described by parametersSymbol valueIf this parameter exists, return the original oneSymbol value(Search first, then create, register in global)
    • Symbol.keyFor(): Returns the registeredSymbol value(can only be returnedSymbol.for()thekey)
    • Object.getOwnPropertySymbols(): returns all that are used as property names in an objectSymbol valueAn array of
  • built-in
    • Symbol.hasInstance: points to an internal method that is used by other objectsThe instanceof operatorThis method is called to determine whether there is an instance of this object
    • Symbol.isConcatSpreadable: refers to a Boolean that defines an object forArray.prototype.concat()Can be expanded when
    • Symbol. Species: Refers to a constructor that is called when an instance object uses its own constructor
    • Symbol.match: refers to a function when the instance object isString.prototype.match()It will be redefined when calledmatch()The behavior of the
    • Symbol.replace: refers to a function when the instance object isString.prototype.replace()It will be redefined when calledreplace()The behavior of the
    • Symbol.search: refers to a function when the instance object isString.prototype.search()It will be redefined when calledsearch()The behavior of the
    • Symbol.split: refers to a function when the instance object isString.prototype.split()It will be redefined when calledsplit()The behavior of the
    • Symbol.iterator: points to a default traverser method when the instance object executesfor-ofThe specified default traverser is invoked
    • Symbol. ToPrimitive: Refers to a function that returns the primitive type value of an instance object when it is converted to that primitive type
    • Symbol.toStringTag: refers to a function when the instance object isObject.prototype.toString()When called, the return value appears intoString()The type of object is represented in the string returned
    • Symbol.unscopables: Points to an object, specifying the use ofwithWhich properties will beWith the environmentTo rule out

The data type

  • Undefined
  • Null
  • String
  • Number
  • Boolean
  • Object(including,Array,Function,Date,RegExp,Error)
  • Symbol

Application scenarios

  • Unique object attribute names: Attribute names of type Symbol are unique and are guaranteed not to conflict with other attribute names
  • Magic string: A specific string or number that occurs multiple times in code and is strongly coupled to the code
  • Traversal attribute name: failedfor-in,for-of,Object.keys(),Object.getOwnPropertyNames(),JSON.stringify()Return, only throughObject.getOwnPropertySymbolsreturn
  • Enable the Singleton pattern for modules: calling a class returns the same instance at any time (windowandglobal), usingSymbol.for()To simulate the globalThe Singleton pattern

The difficult

  • Symbol()A value that generates a primitive type is not an object, thereforeSymbol()Not used beforeThe new command
  • Symbol()Parameter indicates the currentSymbol valueWith the same parametersSymbol()Return values are not equal
  • Symbol valueCannot operate with values of other types
  • Symbol valuethroughString()ortoString()Explicit conversion to a string
  • Symbol valueAs an object property name, this property is a public property, but not a private property
  • Symbol valueAs an object property name, you can only use the square bracket operator ([]) without using the dot operator (.Read)
  • Symbol valueWhen used as an object property name, it is not traversed by a normal method and can be defined for an objectMethods that are not private but are used internally only

Set

Set
  • Definition: A data structure, similar to an array, where member values are unique and have no duplicate values
  • Statement:const set = new Set(arr)
  • Input parameter: YesThe Iterator interfaceData structure of
  • attribute
    • Constructor: constructor that returns a Set
    • Size: Returns the total number of instance members
  • methods
    • Add () : Add the value and return the instance
    • Delete () : deletes the value and returns a Boolean
    • Has () : Checks the value and returns a Boolean
    • Clear () : Clears all members
    • Keys () : returns an object that traverses the property value
    • Values () : Returns an object that traverses the property value
    • Entries () : Returns objects with property values and property values as iterators
    • ForEach () : Uses a callback function to iterate over each member

Application scenarios

  • Deduplicate string:[...new Set(str)].join("")
  • Deduplicate arrays:[...new Set(arr)]orArray.from(new Set(arr))
  • Set the array
    • Statement:const a = new Set(arr1),const b = new Set(arr2)
    • And set:new Set([...a, ...b])
    • Intersection:new Set([...a].filter(v => b.has(v)))
    • Difference set:new Set([...a].filter(v => ! b.has(v)))
  • Map collections
    • Statement:let set = new Set(arr)
    • Mapping:set = new Set([...set].map(v => v * 2))orset = new Set(Array.from(set, v => v * 2))

The difficult

  • Traversal order: insertion order
  • There’s no key, there’s only a value, and you can think of the key and the value as equal
  • Add multipleNaN, only one will existNaN
  • When the same object is added, it is thought to be a different object
  • Casting does not occur when adding values (5! = = "5")
  • keys()andvalues()Is exactly the same,entries()The returned iterator includes both the key and the value and the two values are equal
WeakSet
  • Definition: Similar to the Set structure, member values can only be objects
  • Statement:const set = new WeakSet(arr)
  • Input parameter: YesThe Iterator interfaceData structure of
  • attribute
    • Constructor: returns a WeakSet
  • methods
    • Add () : Add the value and return the instance
    • Delete () : deletes the value and returns a Boolean
    • Has () : Checks the value and returns a Boolean

Application scenarios

  • Store DOM nodes: This member is automatically released when the DOM nodes are removed, without worrying about memory leaks when they are removed from the document
  • Temporarily holds a group of objects or holds information bound to objects: as long as the objects disappear from the outside, it remainsWeakSet structureIs automatically eliminated

The difficult

  • Members areA weak reference, the garbage collection mechanism does not considerWeakSet structureA reference to this member
  • Member is not suitable for reference, it will disappear at any time, so ES6 stipulatesThe WeakSet structure is not traversable
  • When other objects no longer reference the member, the garbage collection mechanism automatically reclaims the memory used by the member, regardless of whether the member still existsWeakSet structureIn the

Map

Map
  • Definition: An object-like data structure where a member key is a value of any type
  • Statement:const set = new Map(arr)
  • Input parameter: YesThe Iterator interfaceAnd each member is a two-element array data structure
  • attribute
    • Constructor: constructor that returns Map
    • Size: Returns the total number of instance members
  • methods
    • Get () : returns a key-value pair
    • Set () : adds a key-value pair and returns the instance
    • Delete () : deletes the key-value pair and returns a Boolean
    • Has () : Checks the key-value pair and returns a Boolean
    • Clear () : Clears all members
    • Keys () : returns the object traversed by the key
    • Values () : Returns an object traversed by a value
    • Entries () : returns objects traversed by keys and values
    • ForEach () : Uses a callback function to iterate over each member

The difficult

  • Traversal order: insertion order
  • If you assign a value to the same key more than once, the later value overrides the previous one
  • A reference to the same object is treated as a key
  • Two instances of the same value are treated as two keys
  • Keys are bound to memory addresses and are considered two keys as long as the memory addresses are different
  • Add more than oneNaNAs a key, there will only be oneNaNValue as a key
  • The Object structureprovideString - valueThe corresponding,Structure of the MapprovideValue -The corresponding
WeakMap
  • Definition: Similar to the Map structure, member keys can only be objects
  • Statement:const set = new WeakMap(arr)
  • Input parameter: YesThe Iterator interfaceAnd each member is a two-element array data structure
  • attribute
    • Constructor: returns a WeakMap
  • methods
    • Get () : returns a key-value pair
    • Set () : adds a key-value pair and returns the instance
    • Delete () : deletes the key-value pair and returns a Boolean
    • Has () : Checks the key-value pair and returns a Boolean

Application scenarios

  • Store DOM nodes: This member key is automatically released when the DOM nodes are removed without worrying about memory leaks when they are removed from the document
  • Deploy private properties: Internal properties are weak references to the instance and disappear when the instance is deleted without causing a memory leak

The difficult

  • Member keys are bothA weak reference, the garbage collection mechanism does not considerWeakMap structureA reference to this member key
  • The member key is not suitable for reference, it will disappear at any time, so ES6 statesThe WeakMap structure is not traversable
  • When other objects no longer reference the member key, the garbage collection mechanism automatically reclaims the memory used by the member, regardless of whether the member still existsWeakMap structureIn the
  • Once the member is no longer needed, the member automatically disappears without manually deleting the reference
  • Weak referencesIt's just the key, not the value, the value is still a normal reference
  • Even if the reference to the member key is removed externally, the internal member value still exists

Proxy

  • Definition: Modifies the default behavior of some operations
  • Statement:const proxy = new Proxy(target, handler)
  • The ginseng
    • Target: intercepts the target object
    • Handler: custom interception behavior
  • methods
    • Proxy.revocable(): Returns a cancelable Proxy instance (returned{ proxy, revoke }Revoke ().)
  • Intercept way
    • Get () : intercepts the reading of object properties
    • Set () : intercepts object property Settings and returns a Boolean
    • has(): Intercepts object property checkk in objTo return to Bull
    • deleteProperty(): Intercepts object property deletiondelete obj[k]To return to Bull
    • defineProperty(): Intercepts object property definitionsObject.defineProperty(),Object.defineProperties()To return to Bull
    • ownKeys(): Intercepts object property traversalfor-in,Object.keys(),Object.getOwnPropertyNames(),Object.getOwnPropertySymbols(), return an array
    • getOwnPropertyDescriptor(): Reads the property description of the intercepting objectObject.getOwnPropertyDescriptor(), return object
    • getPrototypeOf(): Intercepts object prototype readsinstanceof,Object.getPrototypeOf(),Object.prototype.__proto__,Object.prototype.isPrototypeOf(),Reflect.getPrototypeOf(), return object
    • setPrototypeOf(): Intercepts object prototype SettingsObject.setPrototypeOf()To return to Bull
    • isExtensible(): Whether the intercepting object is extensible readObject.isExtensible()To return to Bull
    • preventExtensions(): Intercepts non-extensible Settings for objectsObject.preventExtensions()To return to Bull
    • apply(): Intercepts Proxy instances as function callsproxy(),proxy.apply(),proxy.call()
    • construct(): Intercepts Proxy instance as constructor callnew proxy()

Application scenarios

  • Proxy.revocable(): Do not allow direct access to the object, must be through the proxy access, once the access is finished, the proxy is withdrawn and no further access is allowed
  • get(): Error reading unknown attribute, read value of negative index of array, encapsulate chain operation, generate DOM nested node
  • set(): Data binding (implementation principle of Vue data binding). Ensures that the property value is set properly and prevents external access to the internal property
  • has(): Hides internal attributes from discovery and excludes objects that do not meet attribute conditions
  • deleteProperty(): Protects internal properties from being deleted
  • defineProperty(): prevents properties from being defined externally
  • ownKeys(): Protects internal properties from being traversed

The difficult

  • To make theProxyIt works. It has to be targetedThe instanceTo operate, not toThe target objectoperate
  • When no interceptions are set, the same asDirectly to the original object
  • Property is defined asCannot read/write/extend/configure/enumerateAn error will be reported when using the intercepting method
  • Target object under the proxy, internalthisPoint to theThe Proxy agent

Reflect

  • Definition: keepObject methodsDefault behavior of
  • methods
    • Get () : Returns object properties
    • Set () : sets the object properties and returns a Boolean
    • Has () : Checks object properties and returns a Boolean
    • DeleteProperty () : deletes an object property and returns a Boolean
    • DefineProperty () : Defines object properties and returns a Boolean
    • ownKeys(): Iterates over the object properties, returning an array (Object.getOwnPropertyNames()+Object.getOwnPropertySymbols())
    • GetOwnPropertyDescriptor () : Returns an object property description
    • GetPrototypeOf () : Returns the object prototype, returning the object
    • SetPrototypeOf () : sets the object prototype and returns a Boolean
    • IsExtensible () : returns whether the object isExtensible, returning a Boolean
    • PreventExtensions () : Set object non – extensible, return Boolean
    • Apply () : execute the specified function after binding this
    • Construct () : Call the constructor to create the instance

Designed to

  • willObjectBelong toInternal language methodsIn theReflecton
  • Change some Object method error to returnfalse
  • letThe Object operationbecomeFunction behavior
  • ProxywithReflectComplement each other

Abandoned method

  • Object.defineProperty()= >Reflect.defineProperty()
  • Object.getOwnPropertyDescriptor()= >Reflect.getOwnPropertyDescriptor()

The difficult

  • The Proxy methodandReflect methodOne to one correspondence
  • ProxyandReflectIn combination, the former is responsibleIntercepts assignment operations, who is responsible forThe assignment operation is complete

Data binding: Observer mode

const observerQueue = new Set(a);const observe = fn= > observerQueue.add(fn);
const observable = obj= > new Proxy(obj, {
    set(tgt, key, val, receiver) {
        const result = Reflect.set(tgt, key, val, receiver);
        observerQueue.forEach(v= > v());
        returnresult; }});const person = observable({ age: 25.name: "Yajun" });
const print = () = > console.log(`${person.name} is ${person.age} years old`);
observe(print);
person.name = "Joway";
Copy the code

Class

  • Definition: An abstraction (constructor syntax sugar) of a class of things that have common characteristics
  • Principle: The class itself points to the constructor, where all methods are definedprototypeCan be viewed as another way of writing the constructor (Class === Class.prototype.constructor)
  • Methods and keywords
    • constructor(): constructor,The new commandAutomatically called when the instance is generated
    • Extends: extends the parent class
    • super: of the new superclassthis
    • Static: Defines static property methods
    • Get: The value function that intercepts the value behavior of a property
    • Set: a value saving function that intercepts the value saving behavior of a property
  • attribute
    • __proto__:Constructor inheritance(Always pointing toThe parent class)
    • __proto__.__proto__: the stereotype of the subclass’s stereotype, that is, the stereotype of the superclass (always pointing to the superclass)__proto__)
    • prototype.__proto__:Inheritance of property methods(always refer to the superclassprototype)
  • Static properties: Properties that are assigned after a class is definedIt is not inherited by the instanceCan only be called by a class
  • Static methods: UsestaticDefine the method, the methodIt is not inherited by the instanceCan only be called by a classthisPointing to a class, not an instance)
  • inheritance
    • The essence
      • ES5 essence: Create subclass instances firstthis, and then add the property method of the parent class tothis(Parent.apply(this))
      • ES6 essence: first add the property method of the superclass instance tothis(callsuper()), and then modified with the subclass constructorthis
    • super
      • Called as a function: Can only be called in a constructorsuper()Inside,thisinheritableThe current subclass(super()Called before it can be used in the constructorthis)
      • Called as an object: inCommon methodsIn the pointThe prototype object of the parent classIn theA static methodIn the pointThe parent class
    • Display definition: Useconstructor() { super(); }Define inherited parent class, no written ruleAccording to defined
    • Subclass inherits from parent class: When a subclass uses a property method of the parent class, it must be called in the constructorsuper()Otherwise you don’t get the superclassthis
      • Static property methods of a parent class can be inherited by a child class
      • After a subclass inherits from its parent class, it cansuperCalls the parent class static property method on
  • Instance: Class is equivalent toPrototype of instanceAll property methods defined in the class are inherited by the instance
    • Explicitly specify a property method: usethisSpecify on itself (useClass.hasOwnProperty()Detectable)
    • Implicitly specify property methods: Declare definitions directly on object stereotypes (usingClass.__proto__.hasOwnProperty()Detectable)
  • expression
    • Class expressions:const Class = class {}
    • Name attribute: Return immediatelyclassAfter the name of the class
    • Attribute expression:[prop]
    • Methods the Generator:* mothod() {}
    • Async methods:async mothod() {}
  • This points to an error when an instance property or method is deconstructed
    • Binding this:this.mothod = this.mothod.bind(this)
    • Arrow function:this.mothod = () => this.mothod()
  • Attribute definition location
    • Is defined in the constructor and usesthisPoint to the
    • Defined in theClasses at the top
  • New.target: Determine how the constructor is called

Native constructor

  • String()
  • Number()
  • Boolean()
  • Array()
  • Object()
  • Function()
  • Date()
  • RegExp()
  • Error()

The difficult

  • Calling a method on an instance is essentially calling a method on a prototype
  • Object.assign()It is easy to add multiple methods to a class at once (Object.assign(Class.prototype, { ... }))
  • All methods defined inside the class are non-enumerable (non-enumerable)
  • By default, the constructor returns an instance object (this), you can specify to return another object
  • The value and store functions are set on the propertyDescriptor objecton
  • There is no variable promotion for the class
  • usingnew.target === ClassWrite a class that cannot be used independently and can only be used after inheritance
  • After a child inherits from its parent,thisPoint to a subclass instance, throughsuperIf you assign a value to a property, the assigned property becomes a property of the subclass instance
  • usesuperYou must explicitly specify whether to use it as a function or as an object
  • extendsInheriting not only the class but also the native constructor

Private property method

const name = Symbol("name");
const print = Symbol("print");
class Person {
    constructor(age) {
        this[name] = "Bruce";
        this.age = age;
    }
    [print]() {
        console.log(`The ${this[name]} is The ${this.age} years old`); }}Copy the code

Inherited hybrid class

function CopyProperties(target, source) {
    for (const key of Reflect.ownKeys(source)) {
        if(key ! = ="constructor"&& key ! = ="prototype"&& key ! = ="name") {
            const desc = Object.getOwnPropertyDescriptor(source, key);
            Object.defineProperty(target, key, desc); }}}function MixClass(. mixins) {
    class Mix {
        constructor() {
            for (const mixin of mixins) {
                CopyProperties(this.newmixin()); }}}for (const mixin of mixins) {
        CopyProperties(Mix, mixin);
        CopyProperties(Mix.prototype, mixin.prototype);
    }
    return Mix;
}
class Student extends MixClass(Person.Kid) {}
Copy the code

Module

  • The command
    • export: Specifies the external interface of the module
      • The default is derived:export default Person(You can specify any module name when importing, without knowing the internal real name)
      • Separate export:export const name = "Bruce"
      • On-demand export:export { age, name, sex }(recommended)
      • Renamed the export:export { name as newName }
    • import: Imports internal module functions
      • The default import:import Person from "person"
      • The overall import:import * as Person from "person"
      • According to the need to import:import { age, name, sex } from "person"
      • Renamed the import:import { name as newName } from "person"
      • Since the directed into the:import "person"
      • Composite import:import Person, { name } from "person"
    • Composite patterns:The export commandandThe import commandThe variables are not imported into the current module in essence, which is equivalent to the external forwarding interface. As a result, the current module cannot directly use its imported variables
      • Default Import and Export:export { default } from "person"
      • Overall import and Export:export * from "person"
      • Import and export as needed:export { age, name, sex } from "person"
      • Rename Import and Export:export { name as newName } from "person"
      • Change the name to default import and export:export { name as default } from "person"
      • The default value is named import and export:export { default as name } from "person"
  • Inheritance:The default is derivedandRenamed the exportIn combination, modules can be inherited
  • Design idea: Make it as static as possible so that the dependencies of the module and the variables in and out of the module can be determined at compile time
  • Strict mode: ES6 modules automatically adopt strict mode (whether the module header is added or not)use strict)

Modular solution

  • CommonJS: for servers (dynamic dependencies)
  • AMD: for browsers (dynamic dependency)
  • CMD: for the browser (dynamic dependency)
  • UMD: for browser and server (dynamic dependency)
  • ESM: for browser and server (statically dependent)

Loading way

  • Runtime loading
    • Definition: the whole load module generates an object, then obtains the required properties and methods from the object to load (all load)
    • Impact: This object is only available at runtime, making it impossible to do static optimization at compile time
  • Compile time loading
    • Definition: Load the required properties and methods directly from the module (load on demand)
    • Impact: The module is loaded at compile time, which is more efficient than other schemes, but cannot reference the module itself (itself is not an object), can extend the JS advanced syntax (macros and type verification).

Loading implementation

  • Traditional loadThrough:<script>Load the script synchronously or asynchronously
    • Synchronous loading:<script src=""></script>
    • Defer loads asynchronously:<script src="" defer></script>(Load sequentially and execute after rendering)
    • Async Asynchronous loading:<script src="" async></script>(Load out of order, download and execute)
  • Module is loaded:<script type="module" src=""></script>(The default is Defer, loaded asynchronously)

CommonJS and ESM differences

  • CommonJSThe outputA copy of the value.ESMThe outputThe value of the reference
    • CommonJSOnce a value is output, changes within the module cannot affect it
    • ESMIs a dynamic reference and does not cache values. Variables in a module are bound to the module in which they are located, and when the script is actually executed, the value is evaluated based on this read-only reference to the loaded module
  • CommonJSIs runtime loading,ESMIs loaded at compile time
    • CommonJSLoad modules are objects (i.emodule.exports), this object is generated only after the script has run
    • ESMA load module is not an object, its external interface is just a static definition, which is generated during the static code parsing phase

The Node load

  • Background:CommonJSandESMIncompatible, the current solution is to separate the two and adopt their own loading scheme
  • Distinction: RequirementsESMusing.mjsSuffix file name
    • require()Cannot loadThe MJS file, onlyThe import commandCan only be loadedThe MJS file
    • The MJS fileCannot be used inrequire()Must be usedThe import commandLoad the file
  • Driver:node --experimental-modules file.mjs
  • Restriction: NodeThe import commandCurrently, only local modules can be loaded (File: agreement), the remote module is not supported
  • Load priority
    • The script file omits the suffix: try loading the four suffix files in turn (.mjs,.js,.json,node)
    • None: try to loadpackage.jsontheThe main fieldSpecified script
    • None above: try to load the name asindexFour file extensions (.mjs,.js,.json,node)
    • If the above does not exist, an error is reported
  • Non-existent internal variables:arguments,exports,module,require,this,__dirname,__filename
  • CommonJS load ESM
    • You can’t userequire(), can only be usedimport()
  • ESM load CommonJS
    • automaticallymodule.exportsConverted intoexport default
    • CommonJSThe output caching mechanism is inESMStill valid in load mode
    • usingThe import commandloadingCommonJS moduleIs not allowed to be usedAccording to the need to importShould be used,The default importorThe overall import

Cyclic loading

  • Definition:A scriptExecution dependency ofScript BAnd theA scriptThe execution of theScript B
  • Loading principle
    • CommonJS:require()The first time the script is loaded, the entire script is executed, creating an object cache in memory, and the second time the script is loaded directly from the cache
    • ESM:The import commandThe load variable is not cached, but instead becomes a reference to the loaded module
  • Cyclic loading
    • CommonJS: Output only the parts that have been executed, not the parts that have not been executed
    • ESM: Developers are required to ensure that the actual value can be obtained (variables can be written in the form of functions, functions can be promoted)

The difficult

  • In the ES6 module, the top layerthisPoint to theundefinedShould not be used in top-level codethis
  • A module is a separate file. All variables inside the file are not available externally
  • The export commandThe output interface and its corresponding value areDynamic binding relationship, that is, the real-time internal value of the module can be obtained through this interface
  • The import commandThe variable name in the braces must be the same as the name of the external interface of the module being imported
  • The import commandThe input variable is read-only (essentially the input interface) and cannot be overwritten in the script that loads the module
  • The import commandThe command is promoted to the head of the entire module and is executed first
  • Repeat the same sentenceThe import statementIs executed only once
  • export defaultThe command can be used only once
  • Export the default commandExport the whole module in executionThe import commandCan’t follow afterCurly braces
  • Export the default commandEssentially output a name calleddefaultVariable of, cannot be followed byVariable declaration statement
  • Export the default commandEssentially, assign the following value to the namedefaultAnd you can write the value directly after it
  • Export the default commandandExport {} commandCan exist simultaneously, corresponding toComposite import
  • The export commandandThe import commandCan appear anywhere in a module, as long as it is at the top level of the module, not at block level scope
  • import()After the module is successfully loaded, the module is treated as an objectthen()Can be usedObject to destruct assignmentTo get the output interface
  • This parameter can be used when multiple modules are dynamically loaded at the same timePromise.all()andimport()Combined to achieve
  • import()And in combination withasync/awaitTo write the code for synchronous operations

Singleton mode: cross-module constants

// Constants are shared across files
// person.js
const NAME = "Bruce";
const AGE = 25;
const SEX = "male";
export { AGE, NAME, SEX };
Copy the code
// file1.js
import { AGE } from "person";
console.log(AGE);
Copy the code
// file2.js
import { AGE, NAME, SEX } from "person";
console.log(AGE, NAME, SEX);
Copy the code

Default import swaps overall import

import Person from "person";
console.log(Person.AGE);
Copy the code
import * as Person from "person";
console.log(Person.default.AGE);
Copy the code

Iterator

  • Definition: To provide a uniform access mechanism for various data structures
  • How it works: Create a pointer to the first member and use it in ordernext()Points to the next member, directly to the end (data structures are only deployedThe Iterator interfaceTo complete the traversal operation)
  • role
    • Provide a unified and simple access interface for various data structures
    • Enables the data structure members to be arranged in some order
    • ES6 creates new traversal commandsfor-of.The Iterator interfaceMainly used forfor-ofconsumption
  • Form:for-of(Automatically find the Iterator interface)
  • The data structure
    • Collection:Array,Object,Set,Map
    • Native data structures with interfaces:String,Array,Set,Map,TypedArray,Arguments,NodeList
  • Deployment: The default deployment isSymbol.iteratorThis attribute is consideredIterable)
  • Iterator object
    • next(): Next operation, return{ done, value }(Must be deployed)
    • return():for-ofExit the call early and return{ done: true }
    • throw(): Do not use, cooperateThe Generator functionuse

ForOf cycle

  • Definition: callThe Iterator interfaceGenerate a traverser object (for-ofCalling data structures internallySymbol.iterator())
  • Traversal string:for-inTo obtainThe index.for-ofTo obtainvalue(Recognizes 32-bit UTF-16 characters)
  • Traversing the number group:for-inTo obtainThe index.for-ofTo obtainvalue
  • Iterating over objects:for-inTo obtainkey.for-ofDeploy it on your own
  • Traverse the Set:for-ofTo obtainvalue= >for (const v of set)
  • Through the Map:for-ofTo obtainKey/value pair= >for (const [k, v] of map)
  • Iterating over an array of classes:An object that contains length,The Arguments object,The NodeList object(noAn array of classes for the Iterator interfaceavailableArray.from()Translation)
  • Computationally generated data structures:Array,Set,Map
    • Keys () : returns a traverser object that traverses all keys
    • Values () : Returns a traverser object that traverses all values
    • Entries () : Returns an iterator object that iterates over all key-value pairs
  • withfor-inThe difference between
    • With withfor-inSame neat syntax, but nofor-inThose shortcomings,
    • Different from theforEach(), it can be withbreak,continueandreturnTogether with
    • Provides a uniform operation interface for traversing all data structures

Application scenarios

  • Rewriting hasThe Iterator interfaceOf the data structureSymbol.iterator
  • Deconstruct assignment: Structure a Set
  • Extension operator: will be deployedThe Iterator interfaceConvert the data structure into an array
  • Yield * :yield*Followed by a traversable data structure, its traverser interface is called
  • Functions that take an array as an argument:for-of,Array.from(),new Set(),new WeakSet(),new Map(),new WeakMap(),Promise.all(),Promise.race()

Promise

  • Definition: An object that contains the result of an asynchronous operation
  • state
    • ongoing:pending
    • Has been successfully:resolved
    • Has failed:rejected
  • The characteristics of
    • The state of an object is unaffected
    • Once the state changes it doesn’t change again, it can happen any time
  • Statement:new Promise((resolve, reject) => {})
  • The ginseng
    • resolve: Changes the state fromunfinishedintosuccessfulCalled when the asynchronous operation succeeds and passes the result of the asynchronous operation as a parameter
    • reject: Changes the state fromunfinishedintofailureCalled when the asynchronous operation fails and passes the error of the asynchronous operation as a parameter
  • methods
    • then(): specify separatelyResolved stateandRejected stateCallback function
      • The first parameter: The status changes toresolvedCalled when the
      • The second parameter: The status changes torejected(Optional)
    • Catch () : Specifies the callback function when an error occurs
    • Promise.all(): wrap multiple instances into a new instance and return an array of results after all instances have changed.
      • Input parameter: YesThe Iterator interfaceData structure of
      • Success: Only all instances becomefulfilledThe final state becomesfulfilled
      • Failed: One of the instance states becomesrejectedThe final state is going to berejected
    • Promise.race(): wrap multiple instances into a new instance and return the result of all instance status changes (first changed, first returned)
      • Input parameter: YesThe Iterator interfaceData structure of
      • Success or failure: the state of the instance that changed state first is returned
    • Promise.resolve(): Converts an object to a Promise object (equivalent tonew Promise(resolve => resolve()))
      • Promise instance: Returns the incoming argument intact
      • Thenable object: Convert this object to a Promise object and return (Thenable for includethen()Object to executethen()Equivalent to executing this objectthen())
      • Objects that do not have then(): Converts this object to a Promise object and returns it with a state ofresolved
      • With no arguments: Returns a Promise object in the state ofresolved
    • Promise.reject(): converts an object torejectedPromise object (equivalent tonew Promise((resolve, reject) => reject()))

Application scenarios

  • Loading pictures
  • AJAX to a Promise object

The difficult

  • Only the result of an asynchronous operation determines which state the current is; no other operation can change the state
  • There are only two possible state changes: frompendingintoresolvedAnd from thependingintorejected
  • Once the newPromise objectIt will be executed immediately. There is no way to cancel
  • With no callback function set, internal throws are not reflected externally
  • When inpendingIt is impossible to know the current stage of progress
  • Instance status changesresolvedorrejectedIs triggeredthen()The bound callback function
  • resolve()andreject()Always executes later than the synchronization task in this cycle
  • then()Returns a new instance, after which another one can be calledthen()
  • then()An error thrown during the run will becatch()capture
  • reject()Is equivalent to throwing an error
  • The instance state has changedresolvedThe error is invalid and will not be caught
  • The instance state error hasThe bubblingProperty, it’s passed back until it’s caught, and the error is always the next onecatch()capture
  • Don’t inthen()In the definitionrejectedState callback function (without its second argument)
  • It is recommended to usecatch()Catch errors, do not usethen()Second parameter capture
  • Don’t usecatch()Error capture, instance throw error is not passed to the outer code, i.eThere will be no reaction
  • The instance defined as a parametercatch()And once they arerejectedIt doesn’t triggerPromise.all()thecatch()
  • Promise.reject()Is used as the argument forrejectedBecomes the argument to the subsequent method

Generator

  • Definition: Asynchronous programming solution that encapsulates multiple internal states
  • Form: callThe Generator function(this function does not execute) Returns a pointer object to the internal state (not the run result)
  • Statement:function* Func() {}
  • methods
    • next(): moves the pointer to the next state and returns{ done, value }(Admission is treated as the lastYield command expressionReturn value of)
    • return(): Returns the specified value and terminates the traversalThe Generator functionTo return to{done: true, value: value}
    • throw()In:The Generator functionBody throw error inThe Generator functionError capture in body and return customnew Errow()
  • Yield command: declare the value of internal state (returnThe value returned at the end of the declaration)
    • encounterYield commandSuspend the subsequent operation and take the value of the subsequent expression as the return object’svalue
    • Next time you callnext()The execution continues until the next one is encounteredYield command
    • No more encounterYield commandI’m going to run all the way toThe Generator functionEnd, until meetReturn statementAnd the value of the following expression as the return objectvalue
    • The Generator functionThere is noReturn statementReturns the object’svalueforundefined
  • Yield * command: in aThe Generator functionTo execute the otherThe Generator function(Followed byThe Iterator interfaceData structure)
  • Traversal: Throughfor-ofAutomatically callnext()
  • As an object property
    • All write:const obj = { method: function*() {} }
    • Abbreviations:const obj = { * method() {} }
  • Context: Produced by executionContextOnce meetYield commandIt will temporarily exit the stack (but not disappear), and all variables and objects will be frozen inThe current stateAnd wait until it is executednext()When theContextThe call stack is added again, and the frozen variables and objects resume execution

Methods the similarities and differences

  • Similarities:next(),throw(),return()It’s essentially the same thing, all it does is restore the function and replace it with a different statementYield command
  • The difference between
    • next()Will:Yield commandReplace it with avalue
    • return()Will:Yield commandReplace it with aReturn statement
    • throw()Will:Yield commandReplace it with aThrow statement

Application scenarios

  • Asynchronous operations are expressed synchronously
  • Control flow management
  • Deploy the Iterator interface for the object: putThe Generator functionAssigned to an objectSymbol.iterator, so that the object hasThe Iterator interface
  • As a data structure with an Iterator interface

The difficult

  • Each callnext()The pointer goes fromFunction of the headorWhere we stopped last timeStart execution until the next one is encounteredYield commandorReturn statementSo far,
  • Not inside the functionYield commandBut it will become simpleSuspended function(Still neednext()Trigger)
  • Yield commandIs the flag that suspends execution,next()Is to restore the operation performed
  • Yield commandTo use in another expression must be placed inparenthesesIn the
  • Yield commandUsed as a function argument or to the right of an assignment expressionparentheses
  • Yield commandIf there is no return value of its own, it is considered a returnundefined
  • Yield command expressionEvaluate for inertia, etcnext()This is where the evaluation takes place
  • Function is called to generate a traverser objectSymbol.iteratorIs the object itself
  • At various stages of function operation, throughnext()Inject different values from the outside to the inside to adjust function behavior
  • One of the firstnext()Used to start the traverser object and pass parameters later
  • Want to call for the first timenext()You can put in a value, and you can wrap it around the function
  • Once thenext()Return object’sdonefortrue.for-ofThe traversal is aborted and does not include the returned object
  • Function internal deploymenttry-finallyAnd being executedtry, thenreturn()Will result in immediate entryfinally, the implementation of thefinallyAnd then the whole thing ends
  • The function is not deployed internallytry-catch.throw()Throwing errors will be externaltry-catchcapture
  • throw()Throw error to be caught internally, the premise must beExecute next() at least once
  • throw()Once captured, the next item is executed with itYield command
  • The function has not yet been executedthrow()A throw can only be thrown outside the function

The first time next() passes a value

function Wrapper(func) {
    return function(. args) {
        constgenerator = func(... args); generator.next();returngenerator; }}const print = Wrapper(function* () {
    console.log(`First Input: The ${yield}`);
    return "done";
});
print().next("hello");
Copy the code

ES2016

Numerical extension

  • Exponent operator (**): Numerical exponentiation (equivalent toMath.pow())

Array extension

  • includes(): Indicates whether the specified member exists

ES2017

The statement

  • Shared memory and atomic operations: is a global objectSharedArrayBufferandAtomicsTo store the data in a shared memory spaceJS, the main threadandWeb - worker threadShared between

String extension

  • padStart(): Populates the specified string to the header of the string and returns the new string
  • padEnd(): Populates the specified string to the end of the string and returns the new string

Object extension

  • Object.getOwnPropertyDescriptors(): Returns a description object for all of the object’s own properties (non-inherited properties)
  • Object.values(): Returns an array of values
  • Object.entries(): Returns an array of keys and values

Function extension

  • Function arguments end with a comma: Allows a trailing comma for the last argument of a function

Async

  • Definition: Write an asynchronous function as a synchronous function (Generator function syntax sugar)
  • Principle:The Generator functionAnd the automatic actuatorspawnWrapped in a function
  • Form:The Generator functionthe*replaceasyncThat will beyieldreplaceawait
  • The statement
    • Named function:async function Func() {}
    • Function expression:const func = async function() {}
    • Arrow function:const func = async() => {}
    • Object methods:const obj = { async func() {} }
    • Methods:class Cla { async Func() {} }
  • Await command: waits for the current Promise object to complete its state change
    • Normal: Return the result if the Promise object is followed, otherwise return the corresponding value
    • After theThenable object: equates it to a Promise object returning its result
  • Error handling: willAwait commands Promise objectsIn thetry-catch(can put more than one)

Async improves on Generator

  • Built-in actuator
  • Better semantics
  • Wider applicability
  • The return value is a Promise object

Application scenarios

  • Complete asynchronous operations in sequence

The difficult

  • Async functionreturnPromise object, you can usethen()Add a callback function
  • internalReturn the return valueWill be the nextthen()Out of the cords
  • An internal throw error causes the Promise object returned to beRejected state,catch()To receive
  • The returned Promise object must wait for internal ownershipAwait commands Promise objectsA state change does not occur until the execution is complete, unless encounteredReturn statementorThrow an error
  • Any oneAwait commands Promise objectsintoRejected stateAnd the wholeAsync functionWill interrupt execution
  • It is expected that subsequent asynchronous operations will not be interrupted even if the previous asynchronous operation fails
    • willAwait commands Promise objectsIn thetry-catchIn the
    • Await commands Promise objectsWith acatch()
  • Await commands Promise objectsMay becomeRejected stateIt’s better to put it intry-catchIn the
  • multipleAwait commands Promise objectsIf there is no secondary relationship, it is best to let them both trigger together
  • Await ordersCan only be used inAsync functionOtherwise, an error will be reported
  • Using an arrayforEach()performasync/awaitIt’s not working. It’s workingfor-ofandPromise.all()Instead of
  • The run stack can be preserved with the function contextAsync functionThe execution exists and disappears when the execution is complete

ES2018

String extension

  • Relax the restrictions on string escaping in tag templates: Returns an invalid string escapeundefinedAnd from therawTo get the original string

Object extension

  • Extension operator (…): converts an object to a comma-separated sequence of arguments ({ ...obj }, which is equivalent toRest/spread parametersThe inverse of

Extended application

  • Clone object:const obj = { __proto__: Object.getPrototypeOf(obj1), ... obj1 }
  • Merge objects:const obj = { ... obj1, ... obj2 }
  • Convert a string to an object:{ ..."hello" }
  • Convert an array to an object:{... } [1, 2]
  • Combined with object destruct assignment:const { x, ... rest/spread } = { x: 1, y: 2, z: 3 }(Cannot copy properties inherited from prototype objects)
  • Modify some properties of an existing object:const obj = { x: 1, ... { x: 2 } }

Regular extension

  • S modifier: dotAll pattern modifier to enable.Match any single character (DotAll mode)
  • dotAll: Whether to setS modifier
  • After assertion:xOnly in theyAfter the match
  • A negative assertion follows:xNot onlyyAfter the match
  • Unicode property escape: Match matchUnicode certain propertiesAll characters of
    • Forward matching:\p{PropRule}
    • Reverse matching:\P{PropRule}
    • Limitations:\p{... }and\P{... }Only toUnicode charactersEffective, need to add when usingU modifier
  • Named group matching: specifies a name for each group of matches (? <GroupName>)
    • Form:str.exec().groups.GroupName
    • Deconstruct assignment substitution
      • Statement:const time = "2017-09-11",const regexp = /(? <year>\d{4})-(? <month>\d{2})-(? <day>\d{2})/u
      • Match:time.replace(regexp, "$<day>/$<month>/$<year>")

Promise

  • finally(): Specifies a callback function that will be executed regardless of the final state

Async

  • Asynchronous iterators (for-await-of): loop waiting for eachPromise objectintoResolved stateBefore we go to the next step.

ES2019

String extension

  • Enter U+2028 and U+2029 directly: A string that can be entered directlyLine separatorsandParagraph delimiter
  • JSON. Stringify (): Can return a string that does not meet the UTF-8 standard
  • trimStart(): Removes Spaces from the string header and returns a new string
  • trimEnd(): Removes trailing Spaces and returns a new string

Object extension

  • Object.fromEntries(): returns an object consisting of keys and values (Object.entries()The inverse operation of)

Array extension

  • Sort () stability: The sorting order of items with the same keywords does not change. The default isstable
  • flat(): flattens the array and returns the new array
  • flatMap(): Maps and flattens an array, returning a new array (can only expand one level of an array)

Function extension

  • The toString (): Returns the original code of the function (consistent with the code)
  • The catch() argument can be omitted:catch()The parameters in can be omitted

Symbol

  • descriptionReturns theSymbol valueA description of the

ES2020

The statement

  • globalThis: as a top-level object, pointing to the global environmentthis
    • Browser: The top-level object iswindow
    • Node: The top-level object isglobal
    • WebWorker: The top-level object isself
    • The above three: the generic top-level object isglobalThis

Numerical extension

  • BigInt: any bit integer (new data type, usenAt the end)
    • BigInt() : Converts an ordinary value to BigInt
    • Bigint.asuintn () : Translates BigInt to a value corresponding between 0 and 2n-1
    • Bigint.asintn () : Converts BigInt to -2n-1 to 2n-1-1
    • BigInt.parseInt(): similar toNumber.parseInt()Converts a string to a BigInt in the specified base

The difficult

  • BigInt can also be expressed in a variety of bases, all with suffixes
  • BigInt and ordinary integer are two values, and they are not equal
  • The Typeof operator returns data of type BigIntbigint

Object extension

  • The chain determination operator (? .).: whether an object property exists (returns if noundefinedAnd no further execution)
    • Object properties:obj? .prop,obj? .[expr]
    • Function call:func? . (... args)
  • The null judgment operator (??): Indicates whether the value isundefinedornullIf yes, the default value is used

Regular extension

  • matchAll(): returns all matching iterators

Module

  • import(): Dynamic import (returnedPromise)
    • Background:The import commandIt is statically analyzed by the JS engine, executed before other statements in the module, and cannot be replacedrequire()The dynamic loading function is proposed to be introducedimport()To take the place ofrequire()
    • Location: Can be used anywhere
    • The difference between:require()isSynchronous loading.import()isAsynchronous loading
    • Scenarios: Load on demand, conditional load, and dynamic module path

Iterator

  • For-in traversal order: Have the different engines agreed on how to iterate properties to standardize behavior

Promise

  • Promise.allSettled(): wrap multiple instances into a new instance and return an array of state changes for all instances.
    • Input parameter: YesThe Iterator interfaceData structure of
    • Success: The member is includedstatusandvalue.statusforfulfilled.valueFor the return value
    • Failed: Member containsstatusandreason.statusforrejected.valueFor error reasons

ES proposal

The statement

  • Do expression: Encapsulates a block-level scoped operation, returning the value of the last internal expression executed (do{})
  • Throw expression: Direct usethrow new Error()without(a)or{}including
  • ! # command: Specifies the script executor (written at the beginning of the file)

Numerical extension

  • Numeric separator (_)Use:_As a thousandth separator (to increase the readability of the value)
  • Math.signbit(): Returns whether the value symbol is set

Function extension

  • Function partial execution: Reuse function function (?Represents a single parameter placeholder,.Represents multiple parameter placeholders)
  • The pipe operator (| >): Pass the value of the left expression to the right function for evaluation (f(x)= >x |> f)
  • The binding operator (::): Function binding (object on the left and function on the right, replacebind,apply,callCall)
    • The bind:bar.bind(foo)= >foo::bar
    • Apply:bar.apply(foo, arguments)= >foo::bar(... arguments)

Realm

  • Definition: to provideThe sandbox function, which allows code to be isolated and prevents the isolated code from getting the global object
  • Statement:new Realm().global

Class

  • Static attributesUse:staticDefine a property, the propertyIt is not inherited by the instanceCan only be called by a class
  • Private propertyUse:#Defines a property that can only be accessed within the class
  • Private methodsUse:#Defines a method that can only be accessed inside a class
  • A decoratorUse:@Annotate or modify classes and class methods

Module

  • import.meta: Returns script meta information

Promise

  • Promise.any(): wrap multiple instances into a new instance and return an array of results after all instances have changed.
    • Input parameter: YesThe Iterator interfaceData structure of
    • Success: One of the instance states becomesfulfilledThe final state is going to befulfilled
    • Failed: Only all instances have state changesrejectedThe final state becomesrejected
  • Promise.try(): does not want to distinguish between synchronous and asynchronous functions, wrapping functions as instances, usingthen()Specifies the next process, usingcatch()Capture the error

Async

  • The top Await: allows independent use at the top level of a moduleAwait orders, to borrowawaitSolve the problem of asynchronous module loading)

conclusion

Finally, I will send you a complete ES6 feature map, remember to give me a like oh, it is a kind of encouragement to me. Because the picture is too big to upload, please pay attention to IQ front end or scan the bottom of the article TWO-DIMENSIONAL code, background reply ES6, get high-definition ES6 all features memory map, help you easily remember all features of ES6.

conclusion

❤️ follow + like + collect + comment + forward ❤️, original is not easy, encourage the author to create more high-quality articles

Follow the public accountIQ front-end, a focus on CSS/JS development skills of the front-end public number, more front-end small dry goods waiting for you oh

  • Follow and replydataFree access to study materials
  • Follow and replyInto the group ofPull you into the tech group
  • Welcome to attentionIQ front-endAnd moreCSS/JS development skillsOnly in the public account push