当前位置:网站首页>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 ES2015、ES2016、ES2017、ES2018、ES2019.
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
varExecute in global codeconstandletCan only be executed in code blocks
Assignment use
constA constant must be assigned immediately after it is declaredletVariables can be assigned immediately after declaration or when used
Declaration method :
var、const、let、function、class、import
Key points and difficulties
Duplicate statements are not allowed
Using it without definition will report an error :
constandletNo variable promotionTemporary dead zone : As long as there is... In the block level scope
constandlet, 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 InterfaceDeconstruction assignment in the form of an arrayform :
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 } = packageJsonDefine 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
undefinedDeconstruction follows the matching pattern
When the deconstruction fails, the value of the variable is equal to
undefinedundefinedandnullCan't convert to object , Therefore, it is impossible to deconstruct
String extension
[x] Unicode notation :
Braces containExpress Unicode character (\u{0xXX}or\u{0XXX})[x] String traversal : It can be done by
for-ofTraversal 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 storeOfUnicode characterOn
Numerical expansion
[x] Binary representation :
0b or 0B startFor binary (0bXXor0BXX)[x] Octal representation :
0o or 0O startFor binary (0oXXor0OXX)[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 + nThe 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 isgetandsetOn )bind Return function :
bound Function nameFunction 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、SymbolTraverse
for-in: Traversing objectsIt can inherit and enumerate itselfattributeObject.keys(): Returns the objectItself enumerableAn array of keys of attributesObject.getOwnPropertyNames(): Returns the objectSelf inheritable enumerable non enumerableAn array of keys of attributesObject.getOwnPropertySymbols(): Returns the objectSymbolAn array of keys of attributesReflect.ownKeys(): Returns the objectSelf inheritable enumerable non enumerable SymbolAn 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 torest/spread ParametersThe inverse operation of )[x] Array.from(): The transformation has
Iterator InterfaceThe data structure of is a real array , Return a new arrayClass array object :
contain length The object of、Arguments object、NodeList objectTraversable objects :
String、Set 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 usefor-ofAuto traverse ornext()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
constorletOnce againlength: 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 objectlength: 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
thisThe mechanism of , But there is no one of its ownthis, Leading to internalthisThat's the outer code blockthisBecause no
this, Therefore, it cannot be used as a constructorNo 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
thisyesThe object in which it is definedinstead ofThe object usedAllowing
thisDirectional immobilization , This feature is very useful for encapsulating callback functionsIt cannot be regarded as
Constructors, Therefore, the arrow function cannot be usednew commandNot to be used
yield command, So the arrow function cannot be used asGenerator functionNot to be used
Arguments object, This object does not exist in the function body ( You can userest/spread ParametersInstead 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 isRegular 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 callRegExpThe instance corresponds toRegExp.prototype[Symbol. Method ][x] u Modifier :Unicode Pattern modifier , Correctly handle greater than
\uFFFFOfUnicode characterDot character(.)Unicode notationquantifiersPredefined patternsi Modifierescape
[x] y Modifier : Adhesion modifier , To ensure the match, you must start the global match from the first remaining position ( And
g ModifierWorks 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 ModifierImplied header matching flag^Just one
y ModifierYesmatch()Only the first match can be returned , Must be withg ModifierIn 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 originalSymbol value( Search first and then create , Register in the global environment )Symbol.keyFor(): Return registered
Symbol valueDescription of ( Only returnSymbol.for()Ofkey)Object.getOwnPropertySymbols(): Returns all properties used as property names in an object
Symbol valueArray of
built-in
Symbol.hasInstance: Point to an internal method , When other objects use
instanceof OperatorThis method will be called when determining whether this object is an instanceSymbol.isConcatSpreadable: Point to a Boolean value , Define objects for
Array.prototype.concat()Whether it can be expandedSymbol.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 redefinematch()actSymbol.replace: Point to a function , When the instance object is
String.prototype.replace()When called, it will redefinereplace()actSymbol.search: Point to a function , When the instance object is
String.prototype.search()When called, it will redefinesearch()actSymbol.split: Point to a function , When the instance object is
String.prototype.split()When called, it will redefinesplit()actSymbol.iterator: Point to a default iterator method , When the instance object executes
for-ofWill call the specified default iteratorSymbol.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 intoString()The returned string represents the type of the objectSymbol.unscopables: Point to an object , Specify the use of
withWhich attributes will bewith Environmental Scienceexclude
data type
Undefined
Null
String
Number
Boolean
Object( contain
Array、Function、Date、RegExp、Error)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-in、for-of、Object.keys()、Object.getOwnPropertyNames()、JSON.stringify()return , Only throughObject.getOwnPropertySymbolsreturnEnable module Singleton Pattern : Call a class to return the same instance at any time (
windowandglobal), UseSymbol.for()To simulate the globalSingleton Pattern
Key points and difficulties
Symbol()Generating a value of original type is not an object , thereforeSymbol()Cannot be used beforenew commandSymbol()The parameter represents the currentSymbol valueDescription of , With the same parametersSymbol()The return value is not equalSymbol valueCannot operate with other types of valuesSymbol valueIt can be done byString()ortoString()Explicit conversion to stringSymbol valueAs an object property name , This attribute is public , But not privateSymbol valueAs an object property name , Only square bracket operators can be used ([]) Read , You can't use the dot operator (.) ReadSymbol valueAs an object property name , It will not be traversed by conventional methods , You can use this property to defineMethods 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 InterfaceData structure ofattribute
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)]orArray.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))orset = 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
NaNwhen , There will only be oneNaNWhen adding the same object , Will think it's a different object
No type conversion occurs when adding values (
5 !== "5")keys()andvalues()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 InterfaceData structure ofattribute
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 structureThe reference in will be automatically eliminated
Key points and difficulties
The members are
Weak reference, Garbage collection mechanism does not considerWeakSet structureA reference to this memberMembers are not suitable for reference , It will disappear at any time , therefore ES6 Regulations
WeakSet Structure is not traversableWhen 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 structurein
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 InterfaceAnd each member is a data structure of a two element arrayattribute
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
NaNAs key , There will only be one withNaNAs the value of the keyObject structureProvidecharacter string — valueCorresponding ,Map structureProvidevalue — valueCorresponding
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 InterfaceAnd each member is a data structure of a two element arrayattribute
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 considerWeakMap structureA reference to this member keyMember keys are not suitable for referencing , It will disappear at any time , therefore ES6 Regulations
WeakMap Structure is not traversableWhen 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 structureinOnce no longer needed , Members will disappear automatically , Do not delete references manually
Weakly quoted
Just keys, not values, The value is still a normal referenceEven 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 valuedeleteProperty(): Intercept object attribute deletion
delete obj[k], Returns a Boolean valuedefineProperty(): Intercept object attribute definitions
Object.defineProperty()、Object.defineProperties(), Returns a Boolean valueownKeys(): Intercept object property traversal
for-in、Object.keys()、Object.getOwnPropertyNames()、Object.getOwnPropertySymbols(), Returns an array ofgetOwnPropertyDescriptor(): Intercept object attribute description reading
Object.getOwnPropertyDescriptor(), Returns the objectgetPrototypeOf(): Intercept object prototype reading
instanceof、Object.getPrototypeOf()、Object.prototype.__proto__、Object.prototype.isPrototypeOf()、Reflect.getPrototypeOf(), Returns the objectsetPrototypeOf(): Intercept object prototype settings
Object.setPrototypeOf(), Returns a Boolean valueisExtensible(): Whether the intercepted object is extensible to read
Object.isExtensible(), Returns a Boolean valuepreventExtensions(): The interception object is not extensible
Object.preventExtensions(), Returns a Boolean valueapply(): 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 allowedget(): Error reading unknown attribute 、 Read the value of the negative index of the array 、 Package chain operation 、 Generate DOM Nested nodesset(): 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 externalhas(): Hide internal properties from discovery 、 Exclude objects that do not meet the attribute criteriadeleteProperty(): Protect internal attributes from being deleteddefineProperty(): Prevent attributes from being externally definedownKeys(): Protect internal properties from being traversed
Key points and difficulties
To make
ProxyWork , Must be directed atexampleTo operate , Not againstTarget audienceTo operateWhen no interception is set , Equate to
Go directly to the original objectAttributes are defined as
Can't read or write / Expand / To configure / enumerationwhen , Using the interception method will report an errorThe target object under the agent , Inside
thisPoint toProxy agent
Reflect
Definition : keep
Object MethodDefault behavior ofMethod
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
ObjectBelong toInternal methods of languagePut it inReflectOnCertain certain Object The error condition of the method is changed to return
falseGive Way
Object operationbecomeFunction behaviorProxyAndReflectExist side by side and play a part together
Waste method
Object.defineProperty()=>Reflect.defineProperty()Object.getOwnPropertyDescriptor()=>Reflect.getOwnPropertyDescriptor()
Key points and difficulties
Proxy MethodandReflect MethodOne-to-one correspondenceProxyandReflectA combination of , The former is responsible forIntercept assignment operations, The latter is responsible forComplete 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
prototypeOn , It can be seen as another way to write constructors (Class === Class.prototype.constructor)Methods and keywords
constructor(): Constructors ,
new commandAutomatically call when generating an instanceextends: Inherited parent class
super: Create a new parent class
thisstatic: 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 toParent 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 parentprototype)
Static attribute : After defining the class, assign the attribute , This attribute
Will not be inherited by instance, Can only be called through a classStatic methods : Use
staticDefine methods , The methodWill not be inherited by instance, Can only be called through a class ( MethodsthisPointing 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
superCall the parent static attribute methodCall as function : Can only be called in the constructor
super(), InsidethisPoint to inheritedCurrent subclass(super()It can only be used in the constructor after callingthis)Call... As an object : stay
Common methodPoint toThe prototype object of the parent class, stayStatic methodsPoint toParent classES5 The essence : Create subclass instances first
this, Then add the attribute method of the parent class tothisOn (Parent.apply(this))ES6 The essence : First add the attribute method of the parent class instance to
thisOn ( callsuper()), Then use the subclass constructor to modifythisThe essence
super
Display definition : Use
constructor() { super(); }Define inheritance parent , If there is no writingDisplay definitionSubclass 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 classthis
example : Class is equivalent to
The prototype of the instance, All attribute methods defined in the class will be inherited by the instanceExplicitly specify attribute methods : Use
thisAssign to yourself ( UseClass.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
classClass name afterProperty 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
thisPoint toIt'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 objectThe value taking function and the value saving function are set in the
Descriptor objectOnClass does not have variable Promotion
utilize
new.target === ClassWrite out classes that cannot be used independently and can only be used after inheritanceAfter the subclass inherits the parent class ,
thisPoint to a subclass instance , adoptsuperAssign a value to an attribute , The assigned property becomes a property of the subclass instanceUse
superwhen , You must explicitly specify whether to use as a function or as an objectextendsNot 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 commandandimport commandPut 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 derivedandRename ExportWhen used together, the module can be inheriteddesign 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 asynchronouslySynchronous 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
CommonJSOutputCopy of value,ESMOutputThe value of the referenceCommonJSOnce a value is output , Changes within the module do not affect this valueESMIs 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
CommonJSIs runtime load ,ESMIt is loaded at compile timeCommonJSLoading modules are objects ( namelymodule.exports), This object will only be generated after the script runsESMLoad 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 :
CommonJSandESMNot compatible with each other , The current solution is to separate the two , Adopt their own loading schemesdistinguish : requirement
ESMuse.mjsSuffix filenamerequire()Can't load.mjs file, Onlyimport commandBefore loading.mjs file.mjs fileCan't be used inrequire(), You have to useimport commandLoad the file
drive :
node --experimental-modules file.mjsLimit :Node Of
import commandCurrently, only local modules can be loaded (file: agreement), Loading remote modules is not supportedLoad priority
The script file omits the suffix : Try loading four suffix files in turn (
.mjs、.js、.json、node)The above does not exist : Try loading
package.jsonOfmain FieldThe specified scriptThe above does not exist : Try loading in turn with the name
indexFour suffix files (.mjs、.js、.json、node)The above does not exist : Report errors
Nonexistent internal variables :
arguments、exports、module、require、this、__dirname、__filenameCommonJS load ESM
Out of commission
require(), Only useimport()
ESM load CommonJS
Automatically put
module.exportsTurn it intoexport defaultCommonJSThe output caching mechanism isESMLoading mode is still validuse
import commandloadCommonJS modularwhen , It is not allowed to useImport on demand, You should useThe default importorThe overall import
Cyclic loading
Definition :
Script AThe execution of depends onScript B, andScript AAnd the execution of it depends onScript BLoading 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 cacheESM:
import commandLoad 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
thisPoint toundefined, Should not be used in top-level codethisA module is a separate file , All variables within the file , External cannot get
export commandThe output interface and its corresponding value areDynamic binding relationship, That is, the real-time value inside the module can be obtained through this interfaceimport commandThe variable name in braces must be the same as the name of the external interface of the imported moduleimport commandThe 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 moduleimport commandCommand has promotion effect , It will be lifted to the head of the whole module , First, executeRepeat the same sentence
import sentence, It's only going to be executed onceexport defaultThe command can only be used onceexport default commandExported overall module , In executionimport commandTime cannot followCurly bracesexport default commandThe essence is to output a file nameddefaultThe variable of , Can't followVariable declaration statementsexport default commandThe essence is to assign the following value to a value nameddefaultThe variable of , You can write the value directly afterexport default commandandexport {} commandIt can exist at the same time , CorrespondingComposite importexport commandandimport commandIt can appear anywhere in the module , As long as it is at the top of the module , Cannot be in block level scopeimport()After loading the module successfully , This module will act as an object , Asthen()Parameters of , You can useObject deconstruction assignmentTo get the output interfaceWhen multiple modules are loaded dynamically at the same time , You can use
Promise.all()andimport()Combine to achieveimport()And combineasync/awaitTo 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 deployedIterator InterfaceYou 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 InterfaceMainly forfor-ofconsumption
form :
for-of( Automatically look for Iterator Interface )data structure
aggregate :
Array、Object、Set、MapNative data structures with interfaces :
String、Array、Set、Map、TypedArray、Arguments、NodeList
Deploy : The default deployment is
Symbol.iterator( Having this attribute is consideredErgodic iterable)Traverser object
next(): Next operation , return
{ done, value }( Must be deployed )return():
for-ofEarly exit call , return{ done: true }throw(): Don't use , coordination
Generator functionUse
ForOf loop
Definition : call
Iterator InterfaceGenerate traverser object (for-ofCalling data structures internallySymbol.iterator())Traversal string :
for-inobtainIndexes,for-ofobtainvalue( Recognizable 32 position UTF-16 character )Traversal array :
for-inobtainIndexes,for-ofobtainvalueTraversing objects :
for-inobtainkey,for-ofSelf deployment is requiredTraverse Set:
for-ofobtainvalue=>for (const v of set)Traverse Map:
for-ofobtainKey value pair=>for (const [k, v] of map)Traversal class array :
contain length The object of、Arguments object、NodeList object( nothingIterator InterfaceYou can useArray.from()transformation )Calculate and generate data structure :
Array、Set、Mapkeys(): 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-indifferenceThere are similarities and differences
for-inThe same simple syntax , But there is nofor-inThose shortcomings 、differ
forEach(), It can be connected withbreak、continueandreturnIn combination withProvide a unified operation interface for traversing all data structures
Application scenarios
Rewrite with
Iterator InterfaceOf the data structureSymbol.iteratorDeconstruct assignment : Yes Set Carry on the structure
Extension operator : Will deploy
Iterator InterfaceThe data structure of is converted into an arrayyield*:
yield*Followed by a traversable data structure , Will call its traversal interfaceFunctions that accept arrays as arguments :
for-of、Array.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 :
pendingHave succeeded :
resolvedFailed :
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 airTurn intosuccess, Called when the asynchronous operation succeeds , The result of the asynchronous operation is passed as a parameterreject: Change the state from
Hang in the airTurn intoFailure, 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 , performthen()Equivalent to executing this objectthen())No then() The object of : Convert this object to Promise Object and return , Status as
resolvedWith no arguments : return Promise object , Status as
resolvedEnter the reference : have
Iterator InterfaceData structure ofsuccess : Only all instance states become
resolved, The final state will becomeresolvedFailure : One of the instance states becomes
rejected, The final state will becomerejectedThe first parameter : The status changes to
resolvedCalled when theThe second parameter : The status changes to
rejectedCalled when the ( Optional )then(): Assign separately
resolved stateandrejected stateCallback function forcatch(): 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
rejectedOf Promise object ( Equivalent tonew 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
pendingTurn intoresolved、 frompendingTurn intorejectedOnce new
Promise objectIt will be executed immediately , Unable to cancelDo not set callback function , Internal errors will not be reflected to the outside
When in
pendingwhen , It is impossible to know at what stageThe instance state changes to
resolvedorrejectedwhen , Will triggerthen()Bound callback functionresolve()andreject()The execution of is always later than the synchronization task of this cyclethen()Return to the new instance , Then you can call anotherthen()then()Errors thrown during operation will becatch()Capturereject()Is equivalent to throwing an errorThe instance status has changed to
resolvedwhen , It's invalid to throw another error , Will not be captured , Is equal to not throwingThe error of instance status has
Bubblingnature , It will be passed back until it is captured , Mistakes are always nextcatch()CaptureNot in
then()It definesrejectedCallback function for state ( Do not use its second parameter )It is recommended to use
catch()Capture the error , Do not usethen()Second parameter captureNot used
catch()Capture the error , Instance throwing errors will not be passed to the outer code , namelyThere will be no reactionAs an example of a parameter
catch(), Once beingrejectedIt doesn't triggerPromise.all()Ofcatch()Promise.reject()The parameters of will remain unchanged asrejectedThe 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 lastyield Command expressionThe return value of )return(): Returns the specified value and terminates the traversal
Generator function, return{ done: true, value: Enter the reference }throw(): stay
Generator functionThrow an error outside , stayGenerator functionInternal capture error , Returns a customnew Errow()
yield command : Declare the value of the internal state (
returnThe value returned at the end of the declaration )encounter
yield commandJust pause the next operation , And take the value of the subsequent expression as the value of the return objectvalueNext call
next()when , Continue to execute until you encounter the nextyield commandNo more
yield commandIt runs untilGenerator functionend , Until I metreturn sentenceAnd take the value of the subsequent expression as the value of the return objectvalueGenerator functionNo,return sentenceReturns thevaluebyundefined
yield* command : In a
Generator functionExecute anotherGenerator function( Followed byIterator InterfaceData structure of )Traverse : adopt
for-ofAutomatically callnext()As an object property
Full write :
const obj = { method: function*() {} }Abbreviation :
const obj = { * method() {} }
Context : Execution produces
ContextOnce encounteredyield commandIt's going to exit the stack for a while ( But it doesn't disappear ), All variables and objects will be frozen incurrent state, Wait until it's executednext()when , ThisContextIt 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 replaceyield commandDifference
next(): take
yield commandReplace with avaluereturn(): take
yield commandReplace with areturn sentencethrow(): take
yield commandReplace with athrow sentence
Application scenarios
Asynchronous operation synchronization expression
Control flow management
Deploy for objects Iterator Interface : hold
Generator functionAssigned to the objectSymbol.iterator, So that the object hasIterator InterfaceAs having Iterator Data structure of the interface
Key points and difficulties
Every time you call
next(), The pointer starts fromFunction headerorLast stopStart execution , Until we meet the next oneyield commandorreturn sentenceuntilThere is no need to
yield command, But it will become simpleSuspend function execution( Still neednext()Trigger )yield commandIs a flag to suspend execution ,next()Is to resume the operation performedyield commandWhen used in another expression, it must be placed inparenthesesinyield commandUsed as a function parameter or placed on the right side of the assignment expression , Not to addparenthesesyield commandItself has no return value , It can be considered as returningundefinedyield Command expressionEvaluate for inertia , etc.next()This is the time to evaluateGenerate traverser object after function call , Of this object
Symbol.iteratorIt is the object itselfAt different stages of function operation , adopt
next()Inject different values from the outside to the inside , So we can adjust the function behaviorOne of the first
next()Used to start the traverser object , Parameters can only be passed laterWant to call for the first time
next()You can enter the value , You can wrap another layer outside the functiononce
next()Return object'sdonebytrue,for-ofThe traversal will abort without the return objectFunction internal deployment
try-finallyAnd it's being carried outtry, thatreturn()It will lead to immediate entryfinally, After executionfinallyThen the whole function will endThere is no deployment inside the function
try-catch,throw()Mistakes will be thrown by the outsidetry-catchCapturethrow()Throwing mistakes will be captured internally , The premise is thatAt least once next()throw()After being captured , The next item will be executed incidentallyyield commandThe 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
SharedArrayBufferandAtomicsRealization , Store data in a shared memory space , These data can be found inJS The main threadandweb-worker ThreadsTo 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 functionAnd automatic actuatorsspawnWrapped in a functionform : take
Generator functionOf*Replace withasync, takeyieldReplace withawaitStatement
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 objectPut it intry-catchin ( 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 functionreturnPromise object, You can usethen()Add callback functionInside
return Return valueWill become a follow-upthen()Out of the ginsengAn internal error thrown will result in the return of Promise The object becomes
rejected state, Bycatch()ReceivedBack to Promise The object has to wait until it's internally owned
await command Promise objectThe state changes only after the execution , Unless you meetreturn sentenceorThrow an errorAny one of them
await command Promise objectTurn intorejected state, WholeAsync functionWill interrupt executionIt is hoped that even if the previous asynchronous operation fails, the subsequent asynchronous operation will not be interrupted
take
await command Promise objectPut it intry-catchinawait command Promise objectWith onecatch()
await command Promise objectIt could berejected state, Better put it intry-catchinMultiple
await command Promise objectIf there is no secondary relationship , It's better to let them trigger at the same timeawait commandCan only be used inAsync functionIn , Otherwise, an error will be reportedUsing an array
forEach()performasync/awaitIt will fail , You can usefor-ofandPromise.all()Instead ofThe run stack can be preserved , The function context follows
Async functionThe 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 fromrawThe original string can be obtained on
Object extension
[x] Extension operator (...): Convert the object to a comma separated sequence of parameters (
{ ...obj }, amount torest/spread ParametersThe 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 :
xOnly inyThen it matches[x] Later negative assertion :
xOnly not inyThen it matches[x] Unicode Attribute escape : Match match
Unicode Some attributeAll characters ofForward matching :
\p{PropRule}Reverse matching :
\P{PropRule}Limit :
\p{...}and\P{...}Only rightUnicode characterIt works , Use withu 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})/umatching :
time.replace(regexp, "$<day>/$<month>/$<year>")form :
str.exec().groups.GroupNameDeconstruction 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 objectTurn intoresolved stateBefore moving on to the next step
ES2019
String extension
[x] Direct input U+2028 and U+2029: String can be directly input
Line separatorandSegment 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 valueDescription 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
nending )
Object extension
[x] Chain judgment operator (?.): Whether there are object attributes ( There is no return
undefinedAnd don't go down )[x] Empty judgment operator (??): Whether the value is
undefinedornull, 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
bind、apply、callcall )bind:
bar.bind(foo)=>foo::barapply:
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 , Usecatch()Capture the error
Realm
Definition : Provide
Sandbox function, Allow isolation of code , Prevent isolated code from getting global objectsStatement :
new Realm().global
Class
[x] Static attribute : Use
staticDefining attributes , This attributeWill 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 commandBy JS Engine static analysis , Execute before other statements in the module , Can't replacerequire()The dynamic loading function of , The proposal suggests introducingimport()Instead ofrequire()Location : Can be used anywhere
difference :
require()yes Synchronous loading ,import()yes Load asynchronouslyscene : 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 borrowawaitSolve the problem of asynchronous loading of modules )
边栏推荐
- 冰冰学习笔记:vim工具的基本操作
- 如何实现软件功能安全
- Shell variables, system predefined variables $home, $pwd, $shell, $user, custom variables, special variables $n, $, $*, [email protected],
- 用户登录程序C语言实现
- [openvx] VX for basic use of objects_ node
- [openvx] VX for basic use of objects_ array
- 浅谈——网络安全架构设计(三)
- 测试/开发程序员如何突破?条条大路通罗马......
- 华为再回应“清理34岁以上员工”传言,程序员如何应对“35岁危机”?
- Algorithm --- 2D array mesh migration (kotlin)
猜你喜欢

你知道怎么做好接口测试?
![[GNN report] Li Jia, Hong Kong University of science and technology: Rethinking graph anomaly detection - what kind of graph neural network do we need?](/img/c8/756bac41ed04e128ff543de84928e8.png)
[GNN report] Li Jia, Hong Kong University of science and technology: Rethinking graph anomaly detection - what kind of graph neural network do we need?

svg+js鼠标悬浮视差js特效

【arXiv2022】GroupTransNet: Group Transformer Network for RGB-D Salient Object Detection

编写代码,多个字符从两端移动,向中间汇聚

ospf综合实验配置

Deep parsing Kube scheduler scheduling context

HCIP第九天笔记(OSPF的路由回馈、路由策略、以及配置指南)

What is NFT? You don't know yet!

NanoID 了解一下?比 UUID 更好用
随机推荐
【GNN报告】香港科技大学李佳:图异常检测再思考—我们究竟需要怎样的图神经网络?
浅谈——网络安全架构设计(五)
程序员可能还是程序员,码农可能只能是码农了
Download and installation of mongodb
浅谈——网路安全架构设计(一)
[unity project practice] FSM finite state machine
uva11389
Dark horse programmer - interface testing - four-day learning interface testing - the second day - Interface use case design, test points, function testing, security testing, performance testing, sing
【GNN报告】华为诺亚实验室周敏:曲率视角下的图数据建模与分析
二叉树表达式求值 ~
Entrepreneurial documents: how to write a reminder letter
二叉树遍历(DAY 74)
医院PACS源码 PACS超声科室源码 DICOM影像工作站源码【源码免费分享】
selenium的testng.xml如何写
动态规划及马尔可夫特性最佳调度策略(Matlab完整代码实现)
Binary tree expression evaluation~
Talking about -- network security architecture design (4)
svn: E000022: Can‘t convert string from ‘UTF-8‘ to native encoding 问题解决
【MySQL学习】多个不同版本MySQL安装、MySQL8和MySQL5.7同时安装与使用,压缩版
计划了近半年的跳槽,最终是面试四家,过3家……