当前位置:网站首页>15000 words to summarize all features of ES6

15000 words to summarize all features of ES6

2022-07-23 08:46:00 Ink fragrance^_^

Preface

Read teacher Ruan Yifeng's for the third time 《ECMAScript 6 introduction 》 了 , I didn't read carefully before , Many places are at a glance . Recently, I read word by word , Find a lot of knowledge that you haven't noticed before , For convenience of memory and preview All ES6 characteristic , So write this article .

 As mentioned below 《ECMAScript 6  introduction 》 Unified use 《ES6》 This name replaces , And the latest ES6 The version is also up to the current ES2019.

The knowledge points of this article are completely references or excerpts 《ES6》 The sentence in , There are some sentences for convenience of understanding and memory , Escaped with the same meaning , At the same time, classify and divide the knowledge points . In order for everyone to 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 it, it is recommended to compare 《ES6》 To learn .

The notes sorted out in this article are the essence of the book , It covers the whole ES6 system All features of , It's very convenient for you to get to know each other again All ES6 characteristic . Half an hour of reading is enough for ES6 Have a comprehensive understanding , It can be regarded as a book ES6 Feature dictionary , After collection, you can check it at any time .

ES6 Abbreviation

correct

ES6 yes ECMA by JavaScript Draft article 6 Standard Version , Relevant history can be found in this chapter 《ES6-ECMAScript6 brief introduction 》.

The standards committee finally decided , The standard is every year 6 It was officially released in August and served as the official version of that year , In the next time, we will make changes based on this version , Until next year 6 The monthly draft will naturally become the version of the new year , In this way, the previous version number is not required , Just mark it with the year .ECMAscript 2015 Is in 2015 year 6 month Release ES6 The first version of . And so on ,ECMAscript 2016 yes ES6 Second version of 、 ECMAscript 2017 yes ES6 The third version of .ES6 It is both a historical noun and a general reference , The meaning is 5.1 edition After the JavaScript The next generation of standards , Currently covered ES2015ES2016ES2017ES2018ES2019.

So some articles mentioned ES7( Is essentially ES2016)、ES8( Is essentially ES2017)、ES9( Is essentially ES2018)、ES10( Is essentially ES2019), In essence, they are some nonstandard concepts . from ES1 To ES6, It took several years or even more for each standard to be formulated , You are a ES6 To ES7,ES7 To ES8, It's only been a year , According to this definition , That won't happen soon ES20 了 . In the right sense ES6 Currently covered ES2015(ES6.0)、ES2016(ES6.1)、ES2017(ES6.2)、ES2018(ES6.3)、ES2019(ES6.4).

in addition ,ES6 The updated content is mainly divided into the following points

  • expression : Statement 、 Deconstruct assignment

  • Built-in objects : String extension 、 Numerical expansion 、 Object extension 、 Array extension 、 Function extension 、 Regular extension 、Symbol、Set、Map、Proxy、Reflect

  • Statements and operations :Class、Module、Iterator

  • Asynchronous programming :Promise、Generator、Async

ES2015

Statement

  • [x] const command : declare constant

  • [x] let command : Declare variables

effect

  • Scope

    • Global scope

    • Function scope function() {}

    • Block level scope {}

  • Scope of action

    • var Execute in global code

    • const and let Can only be executed in code blocks

  • Assignment use

    • const A constant must be assigned immediately after it is declared

    • let Variables can be assigned immediately after declaration or when used

  • Declaration method :varconstletfunctionclassimport

Key points and difficulties

  • Duplicate statements are not allowed

  • Using it without definition will report an error :const and let No variable promotion

  • Temporary dead zone : As long as there is... In the block level scope const and let, The declared constants and variables are bound to this region , No more external influences

Deconstruct assignment

  • [x]  String deconstruction const [a, b, c, d, e] = "hello"

  • [x]  Numerical deconstruction const { toString: s } = 123

  • [x]  Boolean deconstruction const { toString: b } = true

  • [x]  Object to deconstruct

    • form :const { x, y } = { x: 1, y: 2 }

    • Default :const { x, y = 2 } = { x: 1 }

    • Change of name :const { x, y: z } = { x: 1, y: 2 }

  • [x]  An array of deconstruction

    • The rules : The data structure has Iterator Interface Deconstruction assignment in the form of an array

    • form :const [x, y] = [1, 2]

    • Default :const [x, y = 2] = [1]

  • [x]  Deconstruction of function parameters

    • An array of deconstruction :function Func([x = 0, y = 1]) {}

    • Object to deconstruct :function Func({ x = 0, y = 1 } = {}) {}

Application scenarios

  • Exchange variable values :[x, y] = [y, x]

  • Return multiple values of the function :const [x, y, z] = Func()

  • Define function parameters :Func([1, 2])

  • extract JSON data :const { name, version } = packageJson

  • Define the default values of function parameters :function Func({ x = 1, y = 2 } = {}) {}

  • Traverse Map structure :for (let [k, v] of Map) {}

  • Input modules specify properties and methods :const { readFile, writeFile } = require("fs")

Key points and difficulties

  • Matching mode : As long as the patterns on both sides of the equal sign are the same , The variable on the left is given the corresponding value

  • Deconstructing assignment rules : As long as the value to the right of the equals sign is not an object or an array , Just turn it into an object

  • Deconstruct the default value effective condition : The attribute value is strictly equal to undefined

  • Deconstruction follows the matching pattern

  • When the deconstruction fails, the value of the variable is equal to undefined

  • undefined and null Can't convert to object , Therefore, it is impossible to deconstruct

String extension

  • [x] Unicode notation Braces contain Express Unicode character (\u{0xXX} or \u{0XXX})

  • [x]  String traversal : It can be done by for-of Traversal string

  • [x]  String template : Enhanced string that can insert variables in one or more lines

  • [x]  The label template : Special calls to function parameters

  • [x] String.raw(): Returns the result of replacing all variables of the string and escaping the slash

  • [x] String.fromCodePoint(): The character corresponding to the return code point

  • [x] codePointAt(): Returns the code point corresponding to the character (String.fromCodePoint() The inverse operation )

  • [x] normalize(): Unify different representations of characters into the same form , return New string (Unicode regularization )

  • [x] repeat(): Repeat the string n Time , return New string

  • [x] matchAll(): Returns all matches of a regular expression in a string

  • [x] includes(): Whether the specified string exists

  • [x] startsWith(): Whether there is a string header specifying the string

  • [x] endsWith(): Whether there is a specified string at the end of the string

Key points and difficulties

  • All the above extension methods can be applied to 4 Byte store Of Unicode character On

Numerical expansion

  • [x]  Binary representation 0b or 0B start For binary (0bXX or 0BXX)

  • [x]  Octal representation 0o or 0O start For binary (0oXX or 0OXX)

  • [x] Number.EPSILON: Minimum accuracy of values

  • [x] Number.MIN_SAFE_INTEGER: Minimum safety value (-2^53)

  • [x] Number.MAX_SAFE_INTEGER: Maximum safety value (2^53)

  • [x] Number.parseInt(): Returns the integer part of the conversion value

  • [x] Number.parseFloat(): Returns the floating-point part of the conversion value

  • [x] Number.isFinite(): Is it a finite value

  • [x] Number.isNaN(): Is it NaN

  • [x] Number.isInteger(): Integer or not

  • [x] Number.isSafeInteger(): Whether it is within the range of numerical safety

  • [x] Math.trunc(): Returns the integer part of a number

  • [x] Math.sign(): Returns the numeric type ( Positive numbers 1 negative -1 zero 0)

  • [x] Math.cbrt(): Returns the value cube root

  • [x] Math.clz32(): Returns the value of 32 Bit unsigned integer form

  • [x] Math.imul(): Returns the multiplication of two values

  • [x] Math.fround(): Returns the value of 32 Bit single precision floating point form

  • [x] Math.hypot(): Returns the square root of the sum of the squares of all values

  • [x] Math.expm1(): return e^n - 1

  • [x] Math.log1p(): return 1 + n The natural logarithm of (Math.log(1 + n))

  • [x] Math.log10(): Return to 10 At the bottom of the n The logarithmic

  • [x] Math.log2(): Return to 2 At the bottom of the n The logarithmic

  • [x] Math.sinh(): return n The hyperbolic sine of

  • [x] Math.cosh(): return n The hyperbolic cosine of

  • [x] Math.tanh(): return n The hyperbolic tangent of

  • [x] Math.asinh(): return n The anti hyperbolic sine of

  • [x] Math.acosh(): return n The anti hyperbolic cosine of

  • [x] Math.atanh(): return n The inverse hyperbolic tangent of

Object extension

  • [x]  Concise representation : Write variables and functions directly as properties and methods of objects ({ prop, method() {} })

  • [x]  Property name expression : Literal defines objects using [] Define key ([prop], Cannot be used with the above )

  • [x]  Methodical name attribute : Return method function name

    • Value function (getter) And the stored value function (setter):get/set Function name ( The description object of the attribute is get and set On )

    • bind Return function :bound Function name

    • Function Function instance returned by constructor :anonymous

  • [x]  Enumerability and traversal of properties : Describing the object enumerable

  • [x] super keyword : Prototype object pointing to the current object ( Can only be used in shorthand methods of objects method() {})

  • [x] Object.is(): Compare whether the two values are equal

  • [x] Object.assign(): Merge objects ( Shallow copy ), Return to the original object

  • [x] Object.getPrototypeOf(): Returns the prototype object of the object

  • [x] Object.setPrototypeOf(): Set the prototype of the object

  • [x] __proto__: Returns or sets the prototype object of the object

Attribute traversal

  • describe : Oneself inheritable enumerable Non enumeration Symbol

  • Traverse

    • for-in: Traversing objects It can inherit and enumerate itself attribute

    • Object.keys(): Returns the object Itself enumerable An array of keys of attributes

    • Object.getOwnPropertyNames(): Returns the object Self inheritable enumerable non enumerable An array of keys of attributes

    • Object.getOwnPropertySymbols(): Returns the object Symbol An array of keys of attributes

    • Reflect.ownKeys(): Returns the object Self inheritable enumerable non enumerable Symbol An array of keys of attributes

  • The rules

    • First, traverse all numeric keys , Arrange in ascending numerical order

    • Second, traverse all string keys , In ascending order of joining time

    • Finally, traverse all Symbol key , In ascending order of joining time

Array extension

  • [x]  Extension operator (...): Convert the array to a comma separated sequence of parameters ([...arr], amount to rest/spread Parameters The inverse operation of )

  • [x] Array.from(): The transformation has Iterator Interface The data structure of is a real array , Return a new array

    • Class array object : contain length The object of Arguments object NodeList object

    • Traversable objects :StringSet structure Map structure Generator function

  • [x] Array.of(): Convert a set of values to a real array , Return a new array

  • [x] copyWithin(): Copy members from the specified location to another location , Return the original array

  • [x] find(): Return the first eligible member

  • [x] findIndex(): Returns the first qualified member index value

  • [x] fill(): Fills the entire array with the specified value , Return the original array

  • [x] keys(): Returns the object with the index value as the traverser

  • [x] values(): Returns an object whose property value is the traverser

  • [x] entries(): Return the object whose index value and property value are traversers

  • [x]  Array space :ES6 Explicitly convert the array space to undefined( There are different rules for handling vacancies , It is recommended to avoid )

Expand applications

  • Clone array :const arr = [...arr1]

  • Merge array :const arr = [...arr1, ...arr2]

  • Mosaic array :arr.push(...arr1)

  • Instead of apply:Math.max.apply(null, [x, y]) => Math.max(...[x, y])

  • Convert string to array :[..."hello"]

  • Convert the class array object to array :[...Arguments, ...NodeList]

  • Convert traversable objects into arrays :[...String, ...Set, ...Map, ...Generator]

  • Combined with array deconstruction assignment :const [x, ...rest/spread] = [1, 2, 3]

  • Calculation Unicode Character length :Array.from("hello").length => [..."hello"].length

Key points and difficulties

  • Use keys()values()entries() Traverser object returned , You can use for-of Auto traverse or next() Manually traverse

Function extension

  • [x]  Parameter default : Specify default values for function parameters

    • Specifying a parameter must not be omitted , Omitting throws an error :function Func(x = throwMissing()) {}

    • Set the default value of the parameter to undefined, Indicates that this parameter can be omitted :Func(undefined, 1)

    • form :function Func(x = 1, y = 2) {}

    • parameter assignment : Lazy evaluation ( Evaluate after function call )

    • Parameter position : Tail parameter

    • Parameter scope : Function scope

    • Declaration method : Default statement , Out-of-service const or let Once again

    • length: Returns the number of parameters without a specified default value

    • Combined with the default value of deconstruction assignment :function Func({ x = 1, y = 2 } = {}) {}

    • application

  • [x] rest/spread Parameters (...): Return redundant parameters of the function

    • form : Exist as an array , There can be no other parameters after

    • effect : Instead of Arguments object

    • length: Returns the number of parameters without a specified default value, but does not include rest/spread Parameters

  • [x]  Strict mode : Operate under strict conditions JS

    • application : As long as function parameters use default values 、 Deconstruct assignment 、 Extension operator , Then the function interior cannot be explicitly set to strict mode

  • [x] name attribute : Returns the function name of the function

    • Assign anonymous functions to variables : An empty string (ES5)、 Variable name (ES6)

    • Assign a named function to a variable : Function name (ES5 and ES6)

    • bind Return function :bound Function name (ES5 and ES6)

    • Function Function instance returned by constructor :anonymous(ES5 and ES6)

  • [x]  Arrow function (=>): Function shorthand

    • Not because there is an internal binding this The mechanism of , But there is no one of its own this, Leading to internal this That's the outer code block this

    • Because no this, Therefore, it cannot be used as a constructor

    • No parameter :() => {}

    • Single parameter :x => {}

    • Multiple parameters :(x, y) => {}

    • Deconstruction parameters :({x, y}) => {}

    • Nesting uses : Deploy the pipeline mechanism

    • this Directional immobilization

  • [x]  Tail call optimization : Only the call frame of the inner function is reserved

    • Definition : The end of the function calls itself

    • effect : As long as tail recursion is used, stack overflow will not occur , Relatively save memory

    • Realization : Rewrite all the internal variables used into the parameters of the function and use the default values of the parameters

    • Definition : The last step in a function is to call another function

    • form :function f(x) { return g(x); }

    • Tail call

    • Tail recursion

Arrow function misunderstanding

  • In function body this yes The object in which it is defined instead of The object used

  • Allowing this Directional immobilization , This feature is very useful for encapsulating callback functions

  • It cannot be regarded as Constructors , Therefore, the arrow function cannot be used new command

  • Not to be used yield command , So the arrow function cannot be used as Generator function

  • Not to be used Arguments object , This object does not exist in the function body ( You can use rest/spread Parameters Instead of )

  • When returning an object, you must put parentheses outside the object

Regular extension

  • [x]  change RegExp Constructor in parameter : The allowed first parameter is Regular objects , The tail parameter is Regular modifier ( The returned regular expression ignores the modifier of the original regular expression )

  • [x]  Regular method call changes : String object match()replace()search()split() Internal call turns into call RegExp The instance corresponds to RegExp.prototype[Symbol. Method ]

  • [x] u Modifier :Unicode Pattern modifier , Correctly handle greater than \uFFFF Of Unicode character

    • Dot character (.)

    • Unicode notation

    • quantifiers

    • Predefined patterns

    • i Modifier

    • escape

  • [x] y Modifier : Adhesion modifier , To ensure the match, you must start the global match from the first remaining position ( And g Modifier Works in a similar way )

  • [x] unicode: Whether to set up u Modifier

  • [x] sticky: Whether to set up y Modifier

  • [x] flags: Modifier for regular expressions

Key points and difficulties

  • y Modifier Implied header matching flag ^

  • Just one y Modifier Yes match() Only the first match can be returned , Must be with g Modifier In combination, all matches can be returned

Symbol

  • Definition : Unique value

  • Statement :const set = Symbol(str)

  • Enter the reference : character string ( Optional )

  • Method

    • Symbol(): Create a description with parameters Symbol value ( Not registered in the global environment )

    • Symbol.for(): Create a description with parameters Symbol value , If this parameter exists, the original Symbol value ( Search first and then create , Register in the global environment )

    • Symbol.keyFor(): Return registered Symbol value Description of ( Only return Symbol.for() Of key)

    • Object.getOwnPropertySymbols(): Returns all properties used as property names in an object Symbol value Array of

  • built-in

    • Symbol.hasInstance: Point to an internal method , When other objects use instanceof Operator This method will be called when determining whether this object is an instance

    • Symbol.isConcatSpreadable: Point to a Boolean value , Define objects for Array.prototype.concat() Whether it can be expanded

    • Symbol.species: Point to a constructor , When the instance object uses its own constructor, it will call the specified constructor

    • Symbol.match: Point to a function , When the instance object is String.prototype.match() When called, it will redefine match() act

    • Symbol.replace: Point to a function , When the instance object is String.prototype.replace() When called, it will redefine replace() act

    • Symbol.search: Point to a function , When the instance object is String.prototype.search() When called, it will redefine search() act

    • Symbol.split: Point to a function , When the instance object is String.prototype.split() When called, it will redefine split() act

    • Symbol.iterator: Point to a default iterator method , When the instance object executes for-of Will call the specified default iterator

    • Symbol.toPrimitive: Point to a function , When the instance object is converted to the value of the original type, the original type value corresponding to this object will be returned

    • Symbol.toStringTag: Point to a function , When the instance object is Object.prototype.toString() When called, its return value will appear in toString() The returned string represents the type of the object

    • Symbol.unscopables: Point to an object , Specify the use of with Which attributes will be with Environmental Science exclude

data type

  • Undefined

  • Null

  • String

  • Number

  • Boolean

  • Object( contain ArrayFunctionDateRegExpError)

  • Symbol

Application scenarios

  • Unique object attribute name : Attribute name belongs to Symbol type , It's all unique , It is guaranteed that it will not conflict with other attribute names

  • Eliminate magic strings : A specific string or value that appears many times in the code and forms a strong coupling with the code

  • Traverse the property name : Unable to get for-infor-ofObject.keys()Object.getOwnPropertyNames()JSON.stringify() return , Only through Object.getOwnPropertySymbols return

  • Enable module Singleton Pattern : Call a class to return the same instance at any time (window and global), Use Symbol.for() To simulate the global Singleton Pattern

Key points and difficulties

  • Symbol() Generating a value of original type is not an object , therefore Symbol() Cannot be used before new command

  • Symbol() The parameter represents the current Symbol value Description of , With the same parameters Symbol() The return value is not equal

  • Symbol value Cannot operate with other types of values

  • Symbol value It can be done by String() or toString() Explicit conversion to string

  • Symbol value As an object property name , This attribute is public , But not private

  • Symbol value As an object property name , Only square bracket operators can be used ([]) Read , You can't use the dot operator (.) Read

  • Symbol value As an object property name , It will not be traversed by conventional methods , You can use this property to define Methods that are not private but are only used internally

Set

Set

  • Definition : Data structure similar to array , Member values are unique and have no duplicate values

  • Statement :const set = new Set(arr)

  • Enter the reference : have Iterator Interface Data structure of

  • attribute

    • constructor: Constructors , return Set

    • size: Returns the total number of instance members

  • Method

    • add(): add value , Return instance

    • delete(): Delete value , Returns a Boolean value

    • has(): Check value , Returns a Boolean value

    • clear(): Clear all members

    • keys(): Returns an object whose property value is the traverser

    • values(): Returns an object whose property value is the traverser

    • entries(): Return the object with attribute value and attribute value as iterators

    • forEach(): Use the callback function to traverse each member

Application scenarios

  • De duplication string :[...new Set(str)].join("")

  • De array :[...new Set(arr)] or Array.from(new Set(arr))

  • Set array

    • Statement :const a = new Set(arr1)const b = new Set(arr2)

    • Combine :new Set([...a, ...b])

    • intersection :new Set([...a].filter(v => b.has(v)))

    • Difference set :new Set([...a].filter(v => !b.has(v)))

  • Mapping set

    • Statement :let set = new Set(arr)

    • mapping :set = new Set([...set].map(v => v * 2)) or set = new Set(Array.from(set, v => v * 2))

Key points and difficulties

  • traversal order : Insertion order

  • There are no keys, only values , It can be considered that the two values of key and value are equal

  • Add multiple NaN when , There will only be one NaN

  • When adding the same object , Will think it's a different object

  • No type conversion occurs when adding values (5 !== "5")

  • keys() and values() The behavior is exactly the same ,entries() The returned iterator includes both keys and values, and the two values are equal

WeakSet

  • Definition : and Set The structure is similar to , Member values can only be objects

  • Statement :const set = new WeakSet(arr)

  • Enter the reference : have Iterator Interface Data structure of

  • attribute

    • constructor: Constructors , return WeakSet

  • Method

    • add(): add value , Return instance

    • delete(): Delete value , Returns a Boolean value

    • has(): Check value , Returns a Boolean value

Application scenarios

  • Store DOM node :DOM Automatically release this member when the node is removed , Don't worry about memory leaks when these nodes are removed from the document

  • Temporarily store a group of objects or information bound to objects : As long as these objects disappear outside , It's in WeakSet structure The reference in will be automatically eliminated

Key points and difficulties

  • The members are Weak reference , Garbage collection mechanism does not consider WeakSet structure A reference to this member

  • Members are not suitable for reference , It will disappear at any time , therefore ES6 Regulations WeakSet Structure is not traversable

  • When other objects no longer reference members , The garbage collection mechanism will automatically recycle the memory occupied by this member , Whether this member still exists in WeakSet structure in

Map

Map

  • Definition : Data structures similar to objects , The member key can be any type of value

  • Statement :const set = new Map(arr)

  • Enter the reference : have Iterator Interface And each member is a data structure of a two element array

  • attribute

    • constructor: Constructors , return Map

    • size: Returns the total number of instance members

  • Method

    • get(): Return key value pair

    • set(): Add key value pair , Return instance

    • delete(): Delete key value pair , Returns a Boolean value

    • has(): Check key value pairs , Returns a Boolean value

    • clear(): Clear all members

    • keys(): Return the object with key as traverser

    • values(): Return the object with value as traverser

    • entries(): Return the object with key and value as iterators

    • forEach(): Use the callback function to traverse each member

Key points and difficulties

  • traversal order : Insertion order

  • Assign multiple values to the same key , The later value will override the previous value

  • A reference to the same object , As a key

  • For two instances of the same value , It is regarded as two keys

  • Key is bound to memory address , As long as the memory address is different, it is regarded as two keys

  • Add multiple to NaN As key , There will only be one with NaN As the value of the key

  • Object structure Provide character string — value Corresponding ,Map structure Provide value — value Corresponding

WeakMap

  • Definition : and Map The structure is similar to , Member keys can only be objects

  • Statement :const set = new WeakMap(arr)

  • Enter the reference : have Iterator Interface And each member is a data structure of a two element array

  • attribute

    • constructor: Constructors , return WeakMap

  • Method

    • get(): Return key value pair

    • set(): Add key value pair , Return instance

    • delete(): Delete key value pair , Returns a Boolean value

    • has(): Check key value pairs , Returns a Boolean value

Application scenarios

  • Store DOM node :DOM Automatically release this member key when the node is removed , Don't worry about memory leaks when these nodes are removed from the document

  • Deploy private properties : Internal attributes are weak references to instances , When you delete instances, they also disappear , No memory leaks

Key points and difficulties

  • Member keys are Weak reference , Garbage collection mechanism does not consider WeakMap structure A reference to this member key

  • Member keys are not suitable for referencing , It will disappear at any time , therefore ES6 Regulations WeakMap Structure is not traversable

  • When other objects no longer reference member keys , The garbage collection mechanism will automatically recycle the memory occupied by this member , Whether this member still exists in WeakMap structure in

  • Once no longer needed , Members will disappear automatically , Do not delete references manually

  • Weakly quoted Just keys, not values , The value is still a normal reference

  • Even if the reference of member key is eliminated externally , The internal member value still exists

Proxy

  • Definition : Modify the default behavior of some operations

  • Statement :const proxy = new Proxy(target, handler)

  • Enter the reference

    • target: Target object of interception

    • handler: Customize the interception behavior

  • Method

    • Proxy.revocable(): Return to cancellable Proxy example ( return { proxy, revoke }, adopt revoke() Cancel the agency )

  • Interception method

    • get(): Block object attribute reading

    • set(): Intercept object attribute settings , Returns a Boolean value

    • has(): Intercept object attribute check k in obj, Returns a Boolean value

    • deleteProperty(): Intercept object attribute deletion delete obj[k], Returns a Boolean value

    • defineProperty(): Intercept object attribute definitions Object.defineProperty()Object.defineProperties(), Returns a Boolean value

    • ownKeys(): Intercept object property traversal for-inObject.keys()Object.getOwnPropertyNames()Object.getOwnPropertySymbols(), Returns an array of

    • getOwnPropertyDescriptor(): Intercept object attribute description reading Object.getOwnPropertyDescriptor(), Returns the object

    • getPrototypeOf(): Intercept object prototype reading instanceofObject.getPrototypeOf()Object.prototype.__proto__Object.prototype.isPrototypeOf()Reflect.getPrototypeOf(), Returns the object

    • setPrototypeOf(): Intercept object prototype settings Object.setPrototypeOf(), Returns a Boolean value

    • isExtensible(): Whether the intercepted object is extensible to read Object.isExtensible(), Returns a Boolean value

    • preventExtensions(): The interception object is not extensible Object.preventExtensions(), Returns a Boolean value

    • apply(): Intercept Proxy Instance is called as a function proxy()proxy.apply()proxy.call()

    • construct(): Intercept Proxy Instance is called as a constructor new proxy()

Application scenarios

  • Proxy.revocable(): Direct access to objects is not allowed , Must be accessed through a proxy , Once the access is over, the proxy is withdrawn and no further access is allowed

  • get(): Error reading unknown attribute 、 Read the value of the negative index of the array 、 Package chain operation 、 Generate DOM Nested nodes

  • set(): Data binding (Vue Implementation principle of data binding )、 Ensure that the property value setting meets the requirements 、 Prevent internal properties from being read and written by external

  • has(): Hide internal properties from discovery 、 Exclude objects that do not meet the attribute criteria

  • deleteProperty(): Protect internal attributes from being deleted

  • defineProperty(): Prevent attributes from being externally defined

  • ownKeys(): Protect internal properties from being traversed

Key points and difficulties

  • To make Proxy Work , Must be directed at example To operate , Not against Target audience To operate

  • When no interception is set , Equate to Go directly to the original object

  • Attributes are defined as Can't read or write / Expand / To configure / enumeration when , Using the interception method will report an error

  • The target object under the agent , Inside this Point to Proxy agent

Reflect

  • Definition : keep Object Method Default behavior of

  • Method

    • get(): Return object properties

    • set(): Setting object properties , Returns a Boolean value

    • has(): Check object properties , Returns a Boolean value

    • deleteProperty(): Delete object properties , Returns a Boolean value

    • defineProperty(): Define object properties , Returns a Boolean value

    • ownKeys(): Traverse object properties , Returns an array of (Object.getOwnPropertyNames()+Object.getOwnPropertySymbols())

    • getOwnPropertyDescriptor(): Return the object property description , Returns the object

    • getPrototypeOf(): Returns the object prototype , Returns the object

    • setPrototypeOf(): Set object prototype , Returns a Boolean value

    • isExtensible(): Returns whether the object is extensible , Returns a Boolean value

    • preventExtensions(): The setting object is not extensible , Returns a Boolean value

    • apply(): binding this Then execute the specified function

    • construct(): Call the constructor to create an instance

Design purpose

  • take Object Belong to Internal methods of language Put it in Reflect On

  • Certain certain Object The error condition of the method is changed to return false

  • Give Way Object operation become Function behavior

  • Proxy And Reflect Exist side by side and play a part together

Waste method

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

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

Key points and difficulties

  • Proxy Method and Reflect Method One-to-one correspondence

  • Proxy and Reflect A combination of , The former is responsible for Intercept assignment operations , The latter is responsible for Complete the assignment operation

Data binding : Observer mode

const observerQueue = newSet();
const observe = fn => observerQueue.add(fn);
const observable = obj =>newProxy(obj, {
    set(tgt, key, val, receiver) {
        const result = Reflect.set(tgt, key, val, receiver);
        observerQueue.forEach(v => v());
        return result;
    }
});

const person = observable({ age: 25, name: "Yajun" });
const print = () =>console.log(`${person.name} is ${person.age} years old`);
observe(print);
person.name = "Joway";

Class

  • Definition : A pair of things having the same abstract characteristics ( Constructor syntax sugar )

  • principle : The class itself points to the constructor , All methods are defined in prototype On , It can be seen as another way to write constructors (Class === Class.prototype.constructor)

  • Methods and keywords

    • constructor(): Constructors ,new command Automatically call when generating an instance

    • extends: Inherited parent class

    • super: Create a new parent class this

    • static: Define static attribute methods

    • get: Value function , Interception attribute value taking behavior

    • set: Stored value function , Intercept the stored value behavior of attributes

  • attribute

    • __proto__ Inheritance of constructors ( Always point to Parent class )

    • __proto__.__proto__: Prototypes of subclasses , That is, the prototype of the parent class ( Always point to the parent __proto__)

    • prototype.__proto__ Inheritance of attribute methods ( Always point to the parent prototype)

  • Static attribute : After defining the class, assign the attribute , This attribute Will not be inherited by instance , Can only be called through a class

  • Static methods : Use static Define methods , The method Will not be inherited by instance , Can only be called through a class ( Methods this Pointing class , Not an instance )

  • Inherit

    • The static attribute method of the parent class can be inherited by the subclass

    • After the subclass inherits the parent class , Can be obtained from super Call the parent static attribute method

    • Call as function : Can only be called in the constructor super(), Inside this Point to inherited Current subclass (super() It can only be used in the constructor after calling this)

    • Call... As an object : stay Common method Point to The prototype object of the parent class , stay Static methods Point to Parent class

    • ES5 The essence : Create subclass instances first this, Then add the attribute method of the parent class to this On (Parent.apply(this))

    • ES6 The essence : First add the attribute method of the parent class instance to this On ( call super()), Then use the subclass constructor to modify this

    • The essence

    • super

    • Display definition : Use constructor() { super(); } Define inheritance parent , If there is no writing Display definition

    • Subclass inherits parent : When the subclass uses the attribute method of the parent class , Must be called in constructor super(), Otherwise, you won't get the parent class this

  • example : Class is equivalent to The prototype of the instance , All attribute methods defined in the class will be inherited by the instance

    • Explicitly specify attribute methods : Use this Assign to yourself ( Use Class.hasOwnProperty() Detectable )

    • Implicitly specify attribute methods : Direct declaration is defined on the object prototype ( Use Class.__proto__.hasOwnProperty() Detectable )

  • expression

    • Class expression :const Class = class {}

    • name attribute : Return immediately class Class name after

    • Property expression :[prop]

    • Generator Method :* mothod() {}

    • Async Method :async mothod() {}

  • this Point to : An error will be reported when deconstructing instance properties or methods

    • binding this:this.mothod = this.mothod.bind(this)

    • Arrow function :this.mothod = () => this.mothod()

  • Attribute definition location

    • Define in constructor and use this Point to

    • It's defined in Class top

  • new.target: Determine how the constructor calls

Native constructor

  • String()

  • Number()

  • Boolean()

  • Array()

  • Object()

  • Function()

  • Date()

  • RegExp()

  • Error()

Key points and difficulties

  • Call methods on instances , The essence is to call the method on the prototype

  • Object.assign() You can easily add multiple methods to a class at a time (Object.assign(Class.prototype, { ... }))

  • All defined methods inside the class are not enumerable (non-enumerable)

  • The constructor returns the instance object by default (this), You can specify to return another object

  • The value taking function and the value saving function are set in the Descriptor object On

  • Class does not have variable Promotion

  • utilize new.target === Class Write out classes that cannot be used independently and can only be used after inheritance

  • After the subclass inherits the parent class ,this Point to a subclass instance , adopt super Assign a value to an attribute , The assigned property becomes a property of the subclass instance

  • Use super when , You must explicitly specify whether to use as a function or as an object

  • extends Not only inheritable classes, but also native constructors

Private property methods

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

Inherit mixed classes

function CopyProperties(target, source) {
    for (const key ofReflect.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, new mixin());
            }
        }
    }
    for (const mixin of mixins) {
        CopyProperties(Mix, mixin);
        CopyProperties(Mix.prototype, mixin.prototype);
    }
    return Mix;
}
class Student extends MixClass(Person, Kid) {}

Module

  • command

    • Default import / export export { default } from "person"

    • Import and export as a whole export * from "person"

    • Import and export on demand export { age, name, sex } from "person"

    • Rename import and Export export { name as newName } from "person"

    • Name change default import and Export export { name as default } from "person"

    • The default name is changed to import and Export export { default as name } from "person"

    • The default import import Person from "person"

    • The overall import import * as Person from "person"

    • Import on demand import { age, name, sex } from "person"

    • Rename import import { name as newName } from "person"

    • Self executing import import "person"

    • Composite import import Person, { name } from "person"

    • The default is derived export default Person( You can specify any name of the module when importing , No need to know the internal real name )

    • Export... Separately export const name = "Bruce"

    • Export... On demand export { age, name, sex }( recommend )

    • Rename Export export { name as newName }

    • export: Specify the external interface of the module

    • import: Import module internal functions

    • Compound mode export command and import command Put them together in a line , The variable is not actually imported into the current module , Equivalent to external forwarding interface , As a result, the current module cannot directly use its imported variables

  • Inherit : The default is derived and Rename Export When used together, the module can be inherited

  • design idea : Try to be static , Make it possible to determine module dependencies at compile time , And the input and output variables

  • Strict mode :ES6 The module automatically adopts strict mode ( Whether or not the module header is added use strict)

Module scheme

  • CommonJS: For servers ( Dynamic dependency )

  • AMD: For browsers ( Dynamic dependency )

  • CMD: For browsers ( Dynamic dependency )

  • UMD: For browsers and servers ( Dynamic dependency )

  • ESM: For browsers and servers ( Static dependency )

Loading mode

  • Load at run time

    • Definition : The overall load module generates an object , Then get the required properties and methods from the object to load ( Load all )

    • influence : Only the runtime can get this object , As a result, static optimization cannot be done at compile time

  • Compile time loading

    • Definition : Get the required attributes and methods directly from the module to load ( Load on demand )

    • influence : Complete module loading at compile time , Efficiency is higher than other schemes , But you cannot reference the module itself ( It's not an object in itself ), Scalable JS Advanced Grammar ( Macro and type verification )

Load implementation

  • Traditional loading : adopt <script> Load scripts synchronously or asynchronously

    • Synchronous loading :<script src=""></script>

    • Defer Load asynchronously :<script src="" defer></script>( Sequential loading , After rendering, execute )

    • Async Load asynchronously :<script src="" async></script>( Load out of order , Download and execute )

  • Module loading <script type="module" src=""></script>( The default is Defer Load asynchronously )

CommonJS and ESM The difference between

  • CommonJS Output Copy of value ,ESM Output The value of the reference

    • CommonJS Once a value is output , Changes within the module do not affect this value

    • ESM Is a dynamic reference and does not cache values , The variables in the module are bound to the module in which they are located , Wait until the script actually executes , Then according to this read-only reference, go to the loaded module to get the value

  • CommonJS Is runtime load ,ESM It is loaded at compile time

    • CommonJS Loading modules are objects ( namely module.exports), This object will only be generated after the script runs

    • ESM Load module is not an object , Its external interface is just a static definition , It will be generated during the static parsing phase of the code

Node load

  • background :CommonJS and ESM Not compatible with each other , The current solution is to separate the two , Adopt their own loading schemes

  • distinguish : requirement ESM use .mjs Suffix filename

    • require() Can't load .mjs file , Only import command Before loading .mjs file

    • .mjs file Can't be used in require(), You have to use import command Load the file

  • drive :node --experimental-modules file.mjs

  • Limit :Node Of import command Currently, only local modules can be loaded (file: agreement ), Loading remote modules is not supported

  • Load priority

    • The script file omits the suffix : Try loading four suffix files in turn (.mjs.js.jsonnode)

    • The above does not exist : Try loading package.json Of main Field The specified script

    • The above does not exist : Try loading in turn with the name index Four suffix files (.mjs.js.jsonnode)

    • The above does not exist : Report errors

  • Nonexistent internal variables :argumentsexportsmodulerequirethis__dirname__filename

  • CommonJS load ESM

    • Out of commission require(), Only use import()

  • ESM load CommonJS

    • Automatically put module.exports Turn it into export default

    • CommonJS The output caching mechanism is ESM Loading mode is still valid

    • use import command load CommonJS modular when , It is not allowed to use Import on demand , You should use The default import or The overall import

Cyclic loading

  • Definition : Script A The execution of depends on Script B, and Script A And the execution of it depends on Script B

  • Loading principle

    • CommonJS:require() The first time the script is loaded, the entire script will be executed , Generate an object in memory and cache it , When the script is loaded twice, it is directly obtained from the cache

    • ESM:import command Load variables are not cached , Instead, it becomes a reference to the loaded module

  • Cyclic loading

    • CommonJS: Output only the executed part , The part that has not been executed will not output

    • ESM: Developers need to ensure that they can get the value when they really get the value ( Variables can be written in functional form , Function has a lifting effect )

Key points and difficulties

  • ES6 Module , top floor this Point to undefined, Should not be used in top-level code this

  • A module is a separate file , All variables within the file , External cannot get

  • export command The output interface and its corresponding value are Dynamic binding relationship , That is, the real-time value inside the module can be obtained through this interface

  • import command The variable name in braces must be the same as the name of the external interface of the imported module

  • import command The input variable is read-only ( The essence is the input interface ), It is not allowed to rewrite the interface in the script that loads the module

  • import command Command has promotion effect , It will be lifted to the head of the whole module , First, execute

  • Repeat the same sentence import sentence , It's only going to be executed once

  • export default The command can only be used once

  • export default command Exported overall module , In execution import command Time cannot follow Curly braces

  • export default command The essence is to output a file named default The variable of , Can't follow Variable declaration statements

  • export default command The essence is to assign the following value to a value named default The variable of , You can write the value directly after

  • export default command and export {} command It can exist at the same time , Corresponding Composite import

  • export command and import command It can appear anywhere in the module , As long as it is at the top of the module , Cannot be in block level scope

  • import() After loading the module successfully , This module will act as an object , As then() Parameters of , You can use Object deconstruction assignment To get the output interface

  • When multiple modules are loaded dynamically at the same time , You can use Promise.all() and import() Combine to achieve

  • import() And combine async/await To write code for synchronous operation

The singleton pattern : Cross module constants

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

The default import is to swap the overall import

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

Iterator

  • Definition : Provide unified access mechanism for different data structures

  • principle : Create a pointer to the first member , Use in order next() Point to the next member , Go directly to the end ( As long as the data structure is deployed Iterator Interface You can complete the traversal operation )

  • effect

    • Provide a unified and simple access interface for various data structures

    • Enable the members of the data structure to be arranged in a certain order

    • ES6 Created a new traversal command for-of,Iterator Interface Mainly for for-of consumption

  • form :for-of( Automatically look for Iterator Interface )

  • data structure

    • aggregate :ArrayObjectSetMap

    • Native data structures with interfaces :StringArraySetMapTypedArrayArgumentsNodeList

  • Deploy : The default deployment is Symbol.iterator( Having this attribute is considered Ergodic iterable)

  • Traverser object

    • next(): Next operation , return { done, value }( Must be deployed )

    • return()for-of Early exit call , return { done: true }

    • throw(): Don't use , coordination Generator function Use

ForOf loop

  • Definition : call Iterator Interface Generate traverser object (for-of Calling data structures internally Symbol.iterator())

  • Traversal string :for-in obtain Indexes ,for-of obtain value ( Recognizable 32 position UTF-16 character )

  • Traversal array :for-in obtain Indexes ,for-of obtain value

  • Traversing objects :for-in obtain key ,for-of Self deployment is required

  • Traverse Set:for-of obtain value  => for (const v of set)

  • Traverse Map:for-of obtain Key value pair  =>  for (const [k, v] of map)

  • Traversal class array : contain length The object of Arguments object NodeList object ( nothing Iterator Interface You can use Array.from() transformation )

  • Calculate and generate data structure :ArraySetMap

    • keys(): Returns the traverser object , Go through all the keys

    • values(): Returns the traverser object , Traverse all the values

    • entries(): Returns the traverser object , Traverse all key value pairs

  • And for-in difference

    • There are similarities and differences for-in The same simple syntax , But there is no for-in Those shortcomings 、

    • differ forEach(), It can be connected with breakcontinue and return In combination with

    • Provide a unified operation interface for traversing all data structures

Application scenarios

  • Rewrite with Iterator Interface Of the data structure Symbol.iterator

  • Deconstruct assignment : Yes Set Carry on the structure

  • Extension operator : Will deploy Iterator Interface The data structure of is converted into an array

  • yield*:yield* Followed by a traversable data structure , Will call its traversal interface

  • Functions that accept arrays as arguments :for-ofArray.from()new Set()new WeakSet()new Map()new WeakMap()Promise.all()Promise.race()

Promise

  • Definition : An object that contains the results of an asynchronous operation

  • state

    • Have in hand pending

    • Have succeeded resolved

    • Failed rejected

  • characteristic

    • The state of the object is not affected by the outside world

    • Once the state changes, it won't change again , This result can be obtained at any time

  • Statement :new Promise((resolve, reject) => {})

  • The ginseng

    • resolve: Change the state from Hang in the air Turn into success , Called when the asynchronous operation succeeds , The result of the asynchronous operation is passed as a parameter

    • reject: Change the state from Hang in the air Turn into Failure , Called when an asynchronous operation fails , And pass the error of asynchronous operation as a parameter

  • Method

    • Promise example : Return to the input parameter intact

    • Thenable object : Convert this object to Promise Object and return (Thenable Include for then() The object of , perform then() Equivalent to executing this object then())

    • No then() The object of : Convert this object to Promise Object and return , Status as resolved

    • With no arguments : return Promise object , Status as resolved

    • Enter the reference : have Iterator Interface Data structure of

    • success : Only all instance states become resolved, The final state will become resolved

    • Failure : One of the instance states becomes rejected, The final state will become rejected

    • The first parameter : The status changes to resolved Called when the

    • The second parameter : The status changes to rejected Called when the ( Optional )

    • then(): Assign separately resolved state and rejected state Callback function for

    • catch(): Specifies the callback function when an error occurs

    • Promise.all(): Wrap multiple instances into a new instance , Returns the result array of all instances after state change ( Complete the changes and then return to )

    • Promise.race(): Wrap multiple instances into a new instance , Returns the result of the priority change of the status of all instances ( Change first and return first )

    • Promise.resolve(): Convert object to Promise object ( Equivalent to new Promise(resolve => resolve()))

    • Promise.reject(): Change the object to a state of rejected Of Promise object ( Equivalent to new Promise((resolve, reject) => reject()))

Application scenarios

  • Loading pictures

  • AJAX turn Promise object

Key points and difficulties

  • Only the result of asynchronous operation can determine the current state , Nothing else can change this state

  • There are only two possibilities for state change : from pending Turn into resolved、 from pending Turn into rejected

  • Once new Promise object It will be executed immediately , Unable to cancel

  • Do not set callback function , Internal errors will not be reflected to the outside

  • When in pending when , It is impossible to know at what stage

  • The instance state changes to resolved or rejected when , Will trigger then() Bound callback function

  • resolve() and reject() The execution of is always later than the synchronization task of this cycle

  • then() Return to the new instance , Then you can call another then()

  • then() Errors thrown during operation will be catch() Capture

  • reject() Is equivalent to throwing an error

  • The instance status has changed to resolved when , It's invalid to throw another error , Will not be captured , Is equal to not throwing

  • The error of instance status has Bubbling nature , It will be passed back until it is captured , Mistakes are always next catch() Capture

  • Not in then() It defines rejected Callback function for state ( Do not use its second parameter )

  • It is recommended to use catch() Capture the error , Do not use then() Second parameter capture

  • Not used catch() Capture the error , Instance throwing errors will not be passed to the outer code , namely There will be no reaction

  • As an example of a parameter catch(), Once being rejected It doesn't trigger Promise.all() Of catch()

  • Promise.reject() The parameters of will remain unchanged as rejected The reason of , Becomes an argument to a subsequent method

Generator

  • Definition : Asynchronous programming solutions that encapsulate multiple internal states

  • form : call Generator function ( This function does not execute ) Returns a pointer to the internal state ( Not the result of running )

  • Statement :function* Func() {}

  • Method

    • next(): Move the pointer to the next state , return { done, value }( Attending the meeting is regarded as the last yield Command expression The return value of )

    • return(): Returns the specified value and terminates the traversal Generator function , return { done: true, value: Enter the reference }

    • throw(): stay Generator function Throw an error outside , stay Generator function Internal capture error , Returns a custom new Errow()

  • yield command : Declare the value of the internal state (return The value returned at the end of the declaration )

    • encounter yield command Just pause the next operation , And take the value of the subsequent expression as the value of the return object value

    • Next call next() when , Continue to execute until you encounter the next yield command

    • No more yield command It runs until Generator function end , Until I met return sentence And take the value of the subsequent expression as the value of the return object value

    • Generator function No, return sentence Returns the value by undefined

  • yield* command : In a Generator function Execute another Generator function ( Followed by Iterator Interface Data structure of )

  • Traverse : adopt for-of Automatically call next()

  • As an object property

    • Full write :const obj = { method: function*() {} }

    • Abbreviation :const obj = { * method() {} }

  • Context : Execution produces Context Once encountered yield command It's going to exit the stack for a while ( But it doesn't disappear ), All variables and objects will be frozen in current state , Wait until it's executed next() when , This Context It will rejoin the call stack , Frozen variables and objects resume execution

Similarities and differences of methods

  • The same thing :next()throw()return() It's essentially the same thing , The function is to make the function resume execution and use different statements to replace yield command

  • Difference

    • next(): take yield command Replace with a value

    • return(): take yield command Replace with a return sentence

    • throw(): take yield command Replace with a throw sentence

Application scenarios

  • Asynchronous operation synchronization expression

  • Control flow management

  • Deploy for objects Iterator Interface : hold Generator function Assigned to the object Symbol.iterator, So that the object has Iterator Interface

  • As having Iterator Data structure of the interface

Key points and difficulties

  • Every time you call next(), The pointer starts from Function header or Last stop Start execution , Until we meet the next one yield command or return sentence until

  • There is no need to yield command , But it will become simple Suspend function execution ( Still need next() Trigger )

  • yield command Is a flag to suspend execution ,next() Is to resume the operation performed

  • yield command When used in another expression, it must be placed in parentheses in

  • yield command Used as a function parameter or placed on the right side of the assignment expression , Not to add parentheses

  • yield command Itself has no return value , It can be considered as returning undefined

  • yield Command expression Evaluate for inertia , etc. next() This is the time to evaluate

  • Generate traverser object after function call , Of this object Symbol.iterator It is the object itself

  • At different stages of function operation , adopt next() Inject different values from the outside to the inside , So we can adjust the function behavior

  • One of the first next() Used to start the traverser object , Parameters can only be passed later

  • Want to call for the first time next() You can enter the value , You can wrap another layer outside the function

  • once next() Return object's done by true,for-of The traversal will abort without the return object

  • Function internal deployment try-finally And it's being carried out try, that return() It will lead to immediate entry finally, After execution finally Then the whole function will end

  • There is no deployment inside the function try-catch,throw() Mistakes will be thrown by the outside try-catch Capture

  • throw() Throwing mistakes will be captured internally , The premise is that At least once next()

  • throw() After being captured , The next item will be executed incidentally yield command

  • The function has not yet started execution , At this time throw() Throwing errors can only be thrown outside the function

For the first time next() Transmissible value

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

ES2016

Numerical expansion

  • [x]  Exponential operators (**): Numerical exponentiation ( amount to Math.pow())

Array extension

  • [x] includes(): Whether there are specified members

ES2017

Statement

  • [x]  Shared memory and atomic operations : By global object SharedArrayBuffer and Atomics Realization , Store data in a shared memory space , These data can be found in JS The main thread and web-worker Threads To share

String extension

  • [x] padStart(): Fills the specified string into the string header , Returns the new string

  • [x] padEnd(): Fills the specified string to the end of the string , Returns the new string

Object extension

  • [x] Object.getOwnPropertyDescriptors(): Return all the attributes of the object ( Non inherited properties ) Description object of

  • [x] Object.values(): Returns an array of values

  • [x] Object.entries(): Returns an array of keys and values

Function extension

  • [x]  Function argument trailing comma : The last argument of a function is allowed to have a trailing comma

Async

  • Definition : Make asynchronous functions written in the form of synchronous functions (Generator Function grammar sugar )

  • principle : take Generator function And automatic actuators spawn Wrapped in a function

  • form : take Generator function Of * Replace with async, take yield Replace with await

  • Statement

    • Named functions :async function Func() {}

    • Function expression :const func = async function() {}

    • Arrow function :const func = async() => {}

    • Object methods :const obj = { async func() {} }

    • Class method :class Cla { async Func() {} }

  • await command : Waiting for the present Promise Object state change completed

    • Normal condition : And then Promise Object returns its result , Otherwise, return the corresponding value

    • Following Thenable object : Equate it with Promise Object returns its result

  • Error handling : take await command Promise object Put it in try-catch in ( You can put more )

Async Yes Generator improvement

  • Built in actuator

  • Better semantics

  • Wider applicability

  • The return value is Promise object

Application scenarios

  • Complete asynchronous operations in sequence

Key points and difficulties

  • Async function return Promise object , You can use then() Add callback function

  • Inside return Return value Will become a follow-up then() Out of the ginseng

  • An internal error thrown will result in the return of Promise The object becomes rejected state , By catch() Received

  • Back to Promise The object has to wait until it's internally owned await command Promise object The state changes only after the execution , Unless you meet return sentence or Throw an error

  • Any one of them await command Promise object Turn into rejected state , Whole Async function Will interrupt execution

  • It is hoped that even if the previous asynchronous operation fails, the subsequent asynchronous operation will not be interrupted

    • take await command Promise object Put it in try-catch in

    • await command Promise object With one catch()

  • await command Promise object It could be rejected state , Better put it in try-catch in

  • Multiple await command Promise object If there is no secondary relationship , It's better to let them trigger at the same time

  • await command Can only be used in Async function In , Otherwise, an error will be reported

  • Using an array forEach() perform async/await It will fail , You can use for-of and Promise.all() Instead of

  • The run stack can be preserved , The function context follows Async function The implementation of , When the execution is completed, it disappears

ES2018

String extension

  • [x]  Relax the restrictions on string escape in label template : An illegal string escape was encountered and returned undefined, And from raw The original string can be obtained on

Object extension

  • [x]  Extension operator (...): Convert the object to a comma separated sequence of parameters ({ ...obj }, amount to rest/spread Parameters The inverse operation of )

Expand applications

  • Clone objects :const obj = { __proto__: Object.getPrototypeOf(obj1), ...obj1 }

  • Merge objects :const obj = { ...obj1, ...obj2 }

  • Convert string to object :{ ..."hello" }

  • Convert array to object :{ ...[1, 2] }

  • Combined with object deconstruction assignment :const { x, ...rest/spread } = { x: 1, y: 2, z: 3 }( Properties inherited from prototype objects cannot be copied )

  • Modify some properties of existing objects :const obj = { x: 1, ...{ x: 2 } }

Regular extension

  • [x] s Modifier :dotAll Pattern modifier , send . Match any single character (dotAll Pattern )

  • [x] dotAll: Whether to set up s Modifier

  • [x]  The latter asserts that x Only in y Then it matches

  • [x]  Later negative assertion x Only not in y Then it matches

  • [x] Unicode Attribute escape : Match match Unicode Some attribute All characters of

    • Forward matching :\p{PropRule}

    • Reverse matching :\P{PropRule}

    • Limit :\p{...} and \P{...} Only right Unicode character It works , Use with u Modifier

  • [x]  Named group matching : Give each group a name (?<GroupName>)

    • Statement :const time = "2017-09-11"const regexp = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u

    • matching :time.replace(regexp, "$<day>/$<month>/$<year>")

    • form :str.exec().groups.GroupName

    • Deconstruction assignment substitution

Promise

  • [x] finally(): Specify the callback function that will be executed regardless of the final state

Async

  • [x]  Asynchronous iterator (for-wait-of):, Loop waiting for each Promise object Turn into resolved state Before moving on to the next step

ES2019

String extension

  • [x]  Direct input U+2028 and U+2029: String can be directly input Line separator and Segment separator

  • [x] JSON.stringify() reform : Can return non conformance UTF-8 Standard string

  • [x] trimStart(): Eliminate the space at the beginning of the string , Returns the new string

  • [x] trimEnd(): Eliminate spaces at the end of the string , Returns the new string

Object extension

  • [x] Object.fromEntries(): Returns an object consisting of keys and values (Object.entries() The inverse operation )

Array extension

  • [x] flat(): Flatten an array , Return a new array

  • [x] flatMap(): Map and flatten the array , Return a new array ( Only one level array can be expanded )

Function extension

  • [x] toString() reform : Return the original code of the function ( Consistent with the code )

  • [x] catch() Parameters can be omitted catch() Parameters in can be omitted

Symbol

  • [x] description: return Symbol value Description of

ES The proposal

Statement

  • [x] globalThis object : As a top-level object , Point to... In the global environment this

  • [x] do expression : Encapsulate the operation of the block level scope , Return the value of the internal last execution expression (do{})

  • [x] throw expression : Use it directly throw new Error(), There is no need to () or {} Include

  • [x] !# command : Specify the script executor ( Write it on the first line of the document )

Numerical expansion

  • [x]  Numeric separator (_): Use _ As a thousandth separator ( Increase the readability of values )

  • [x] BigInt(): Create an integer with any number of digits ( New data types , Use n ending )

Object extension

  • [x]  Chain judgment operator (?.): Whether there are object attributes ( There is no return undefined And don't go down )

  • [x]  Empty judgment operator (??): Whether the value is undefined or null, If yes, use the default

Function extension

  • [x]  The function partially executes : Reuse function (? Represents a placeholder for a single parameter ,... Represents multiple parameter placeholders )

  • [x]  Pipe operators (|>): Pass the value of the expression on the left to the function on the right for evaluation (f(x) => x |> f)

  • [x]  Binding operator (::): Function binding ( On the left is the object and on the right is the function , replace bindapplycall call )

    • bind:bar.bind(foo) => foo::bar

    • apply:bar.apply(foo, arguments) => foo::bar(...arguments)

Proxy

  • [x] Promise.try(): I don't want to distinguish between synchronous and asynchronous functions , The wrapper function is an example , Use then() Specify the next process , Use catch() Capture the error

Realm

  • Definition : Provide Sandbox function , Allow isolation of code , Prevent isolated code from getting global objects

  • Statement :new Realm().global

Class

  • [x]  Static attribute : Use static Defining attributes , This attribute Will not be inherited by instance , Can only be called through a class

  • [x]  Private property : Use # Defining attributes , This property can only be accessed inside the class

  • [x]  Private method : Use # Define methods , This method can only be accessed inside a class

  • [x]  Decorator : Use @ Annotate or modify classes and class methods

Module

  • [x] import(): Dynamic import ( return Primise)

    • background :import command By JS Engine static analysis , Execute before other statements in the module , Can't replace require() The dynamic loading function of , The proposal suggests introducing import() Instead of require()

    • Location : Can be used anywhere

    • difference :require() yes Synchronous loading ,import() yes Load asynchronously

    • scene : Load on demand 、 Conditional loading 、 Module path dynamic

  • [x] import.meta: Return script meta information

Async

  • [x]  top floor Await: Allow independent use at the top level of the module await command ( To borrow await Solve the problem of asynchronous loading of modules )

     

原网站

版权声明
本文为[Ink fragrance^_^]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207222351004073.html