Special statement: The original is not easy, shall not be reproduced without authorization or plagiarism, if you need to reprint can contact the author authorization
preface
The third time to read ruan Yifeng teacher “ES6 standard introduction”, before the reading is not careful, many places are a glance ten lines. In my recent reading, I have been reading word by word and found many knowledge points that I didn’t notice before. I am writing this article for the convenience of memorizing and previewing all ES6 features.
The ES6 Standard Introduction mentioned below uses the name ES6 instead, and the latest version of ES6 is up to the current ES2020Copy the code
The knowledge points in this paper are completely referenced or excerpted from the sentences in ES6. In order to facilitate understanding and memory, some sentences are escaped with the same meaning, and the knowledge points are classified and divided at the same time. In order to let you concentrate on remembering these features, there is no nonsense or digression in the full text. All modules are written in the form of notes. If you are not used to reading, it is recommended to study by referring to the content of ES6.
The notes collected in this article are the highlights of the book, covering all the features of the ES6 system, and are very convenient for you to re-understand all the features of ES6. Half an hour of reading will give you a comprehensive understanding of ES6, which can be regarded as a small dictionary of ES6 features. After collecting, you can refer to it at any time. Even if you can’t finish reading, pull to the end of this article, there is a big Easter egg, hee hee!
correction
ES6 is ECMA’s sixth standard version for JavaScript. For a history, see the section ES6- Introduction to ECMAScript6.
In the end, the standards committee decided that the standard would be released in June of each year as the official version of that year, and that changes would be made from that version until June of the following year, when the draft would naturally become the New Year’s version, so that the previous version number would not be needed, and only the year would be used. ECMAscript 2015 was the first release of ES6 in June 2015. ECMAscript 2016 is the second version of ES6, and ECMAscript 2017 is the third version of ES6. ES6 is both a historical term and a general term, referring to the next generation of JavaScript standards after version 5.1, which currently covers ES2015, ES2016, ES2017, ES2018, ES2019, ES2020.
So ES7(essentially ES2016), ES8(essentially ES2017), ES9(essentially ES2018), ES10(essentially ES2019), ES11(essentially ES2020) mentioned in some articles are essentially non-standard concepts. From ES1 to ES6, each standard took several years or even more than a decade to develop, you have an ES6 to ES7, ES7 to ES8, in a year, by this definition, that is not very soon ES20. To put the concept in perspective, ES6 currently covers ES2015, ES2016, ES2017, ES2018, ES2019, ES2020.
In addition, the content of ES6 update is mainly divided into the following points
- Expressions: declare and deconstruct assignments
- Built-in objects: String extension, numeric extension, object extension, array extension, function extension, regular extension, Symbol, Set, Map, Proxy, Reflect
- Statements and operations: Class, Module, Iterator
- Asynchronous programming: Promise, Generator, and Async
ES2015
The statement
- Const command: Declare constants
- The let commandDeclare variables
role
- scope
- Global scope
- Function scope:
function() {}
- Block-level scope:
{}
- scope
Var command
Execute in global codeConst command
andThe let command
Can only be executed in a code block
- Assignment using
Const command
Constants must be assigned immediately after they are declaredThe let command
Variables can be assigned immediately after they are declared or when they are used
- Declaration method:
var
,const
,let
,function
,class
,import
The difficult
- Repeated declarations are not allowed
- Error:
Const command
andThe let command
There is no variable promotion - Temporary dead zones: Used within code blocks
Const command
andThe let command
A variable is not available until it is declared
Deconstruction assignment
- String deconstruction:
const [a, b, c, d, e] = "hello"
- Numerical deconstruction:
const { toString: s } = 123
- Boolean deconstruction:
const { toString: b } = true
- Object to deconstruct
- Form:
const { x, y } = { x: 1, y: 2 }
- The default:
const { x, y = 2 } = { x: 1 }
- Name:
const { x, y: z } = { x: 1, y: 2 }
- Form:
- An array of deconstruction
- Rules: Data structures have
The Iterator interface
Destructible assignments can take the form of arrays - Form:
const [x, y] = [1, 2]
- The default:
const [x, y = 2] = [1]
- Rules: Data structures have
- Function parameter decomposition
- Array deconstruction:
function Func([x = 0, y = 1]) {}
- Object deconstruction:
function Func({ x = 0, y = 1 } = {}) {}
- Array deconstruction:
Application scenarios
- Exchange variable values:
[x, y] = [y, x]
- Returns multiple values to a function:
const [x, y, z] = Func()
- Define function parameters:
Func([1, 2])
- Extract JSON data:
const { name, version } = packageJson
- Define default values for function arguments:
function Func({ x = 1, y = 2 } = {}) {}
- Traversing the Map structure:
for (let [k, v] of Map) {}
- The input module specifies the properties and methods:
const { readFile, writeFile } = require("fs")
The difficult
- Matching patterns: As long as the patterns on both sides of the equals sign are the same, the variables on the left are assigned their corresponding values
- Destruct assignment rule: As long as the value to the right of the equal sign is not an object or an array, convert it to an object first
- Destruct default value Valid condition: the value of the property must be equal to
undefined
- Deconstruction follows a matching pattern
- The value of the variable when the deconstruction fails is equal to
undefined
undefined
andnull
Cannot be converted to an object and therefore cannot be deconstructed
String extension
- Unicode representation:
Curly braces contain
Represents Unicode characters (\u{0xXX}
or\u{0XXX}
) - String traversal: by
for-of
Traversal string - String template: an enhanced string with single or multiple lines and insertable variables
- The label template: A special call to a function argument
- String.raw(): Returns the result of replacing all the variables in the string and escaping the slash
- String.fromCodePoint(): The character corresponding to the return code point
- codePointAt(): returns the corresponding character code point (
String.fromCodePoint()
The inverse operation of) - normalize(): unify the different expressions of characters into the same form and return
A new string
(Unicode normalization) - repeat(): repeats the string n times and returns
A new string
- matchAll(): returns all matches of the regular expression in the string
- includes(): Indicates whether a specified string exists
- startsWith(): Whether a string header exists to specify a string
- endsWith(): Specifies whether there is a string tail
The difficult
- All of the above extension methods can be applied to cause
4 bytes for storage
theUnicode characters
on
Numerical extension
- Binary notation:
It starts with 0B or 0B
Represent binary (0bXX
or0BXX
) - Octal notation:
Start with 0o or 0o
Represent binary (0oXX
or0OXX
) - Number.EPSILON: Minimum numerical precision
- Number.MIN_SAFE_INTEGER: Minimum safe value (
- 2 ^ 53
) - Number.MAX_SAFE_INTEGER: Maximum safety value (
2 ^ 53
) - Number.parseInt(): Returns the integer portion of the converted value
- Number.parseFloat(): Returns the floating point portion of the converted value
- Number.isFinite(): Indicates whether the value is a finite value
- Number.isNaN(): Indicates whether the value is NaN
- Number.isInteger(): Whether the value is an integer
- Number.isSafeInteger(): Whether the value is within the safe range
- Math.trunc(): Returns the integer part of the value
- Math.sign(): returns a numeric type (
A positive number 1
,A negative number - 1
,Zero zero
) - Math.cbrt(): returns a numeric cube root
- Math.clz32(): Returns a 32-bit unsigned integer of a value
- Math.imul(): Returns the multiplication of two values
- Math.fround(): Returns a 32-bit single-precision floating point form of a value
- Math.hypot(): Returns the square root of all numeric sums of squares
- Math.expm1()Returns the
e^n - 1
- Math.log1p()Returns the
1 + n
The natural log of (Math.log(1 + n)
) - Math.log10(): returns logarithm base 10 of n
- Math.log2(): returns logarithm base 2 of n
- Math.sinh()Returns the hyperbolic sine of n
- Math.cosh(): returns the hyperbolic cosine of n
- Math.tanh(): returns the hyperbolic tangent of n
- Math.asinh()Returns the inverse hyperbolic sine of n
- Math.acosh()Returns the inverse hyperbolic cosine of n
- Math.atanh(): returns the inverse hyperbolic tangent of n
Object extension
- Simple notation: Writes variables and functions directly as properties and methods of objects (
{ prop, method() {} }
) - Attribute name expression: is used to define an object
[]
Define key ([prop]
Cannot be used at the same time as above) - Method name attribute: Returns the name of the method function
- Getters and setters:
Get/set the function name
The description object of the property is inget
andset
On) - Function returned by bind:
Bound function name
- The Function constructor returns an instance of the Function:
anonymous
- Getters and setters:
- The enumerability and traversal of properties: Describing an object
enumerable
- The super keyword: refers to the prototype object of the current object (used only in shorthand methods of objects
method() {}
) - Object.is(): Compares two values for equality
- Object.assign(): Merges the object (shallow copy) and returns the original object
- Object.getPrototypeOf(): returns the prototype object of the object
- Object.setPrototypeOf(): Sets the prototype object of the object
- __proto__: Returns or sets the prototype object of the object
Attribute traversal
- Description:
Their own
,inheritable
,Can be enumerated
,The enumeration
,Symbol
- traverse
for-in
: Traverses the objectItself can inherit and enumerate
attributeObject.keys()
: returns an objectSelf enumerable
An array of property keysObject.getOwnPropertyNames()
: returns an objectIts not the Symbol
An array of property keysObject.getOwnPropertySymbols()
: returns an objectIts Symbol
An array of property keysReflect.ownKeys()
: returns an objectIts all
An array of property keys
- The rules
- The first step is to iterate through all the numeric keys in ascending order
- The next step is to iterate over all the string keys in ascending order by the time they were added
- Finally, all Symbol keys are traversed in ascending order by time of addition
Array extension
- Extension operator (…): converts an array to a comma-separated sequence of arguments (
[...arr]
, which is equivalent toRest/spread parameters
The inverse of - Array.from(): The transformation has
The Iterator interface
The data structure is a true array and returns the new array- Array-like objects:
An object that contains length
,The Arguments object
,The NodeList object
- Traversable objects:
String
,The Set structure
,Structure of the Map
,The Generator function
- Array-like objects:
- Array.of(): converts a set of values to a true array and returns the new array
- copyWithin(): copies members from a specified location to another location, returning the original array
- find(): Returns the first eligible member
- findIndex(): returns the first member index that meets the criteria
- fill(): Populates the entire array with the specified value and returns the original array
- keys(): returns an object traversed by an index
- values(): Returns an object that traverses the property value
- entries(): Returns an object with index and property values as iterators
- An array of space: ES6 explicitly converts array vacancies to
undefined
(It is recommended to avoid empty space because of different processing rules)
Extended application
- Clone an array:
const arr = [...arr1]
- Merge arrays:
const arr = [...arr1, ...arr2]
- Splicing arrays:
arr.push(... arr1)
- Instead of the apply:
Math.max.apply(null, [x, y])
= >Math.max(... [x, y])
- Convert a string to an array:
[..."hello"]
- Convert array-like objects to arrays:
[...Arguments, ...NodeList]
- Convert a traversable object to an array:
[...String, ...Set, ...Map, ...Generator]
- Combined with array destruct assignment:
const [x, ...rest/spread] = [1, 2, 3]
- Calculate Unicode character length:
Array.from("hello").length
= >[..."hello"].length
The difficult
- use
keys()
,values()
,entries()
The returned iterator object is availablefor-of
Automatic traversal ornext()
Manual traverse
Function extension
- Parameter Default values: Specifies default values for function arguments
- Form:
function Func(x = 1, y = 2) {}
- Parameter assignment: lazy evaluation (evaluated after the function is called)
- Parameter position: tail parameter
- Parameter scope: Function scope
- Declaration mode: The default declaration cannot be used
const
orlet
Once again - Length: Returns the number of parameters without a default value
- Combined with the destruct assignment default:
function Func({ x = 1, y = 2 } = {}) {}
- application
- Specifies that an argument must not be omitted, otherwise an error is thrown:
function Func(x = throwMissing()) {}
- Set the parameter default to
undefined
, indicating that this parameter can be omitted:Func(undefined, 1)
- Specifies that an argument must not be omitted, otherwise an error is thrown:
- Form:
- Rest/spread parameter (…).: Returns extra arguments to the function
- Form: exists as an array, after which there can be no other arguments
- Function: replace
The Arguments object
- Length: Returns the number of parameters with no default value but not included
Rest/spread parameters
- Strict mode: Run JS under strict conditions
- Application: As long as function parameters use default values, destruct assignments, and extend operators, then functions cannot be explicitly set to strict mode internally
- The name attribute: Returns the name of the function
- Assign an anonymous function to a variable:
An empty string
(ES5),The variable name
(ES6) - Assign a named function to a variable:
The function name
(ES5 and ES6) - Function returned by bind:
Bound function name
(ES5 and ES6) - The Function constructor returns an instance of the Function:
anonymous
(ES5 and ES6)
- Assign an anonymous function to a variable:
- Arrow function (=>): is short for function
- No arguments:
() = > {}
- Single parameter:
x => {}
- Multiple parameters:
(x, y) => {}
- Destruct parameters:
({x, y}) => {}
- Nested use: Deploy the pipeline mechanism
- This refers to immobilization
- It’s not because there’s an internal binding
this
Instead of having its own mechanism at allthis
, resulting in internalthis
It’s the outer code blockthis
- Because there is no
this
, and therefore cannot be used as a constructor
- It’s not because there’s an internal binding
- No arguments:
- Tail call optimization: Only the call frames of inner functions are retained
- The tail call
- Definition: The last step in a function is to call another function
- Form:
function f(x) { return g(x); }
- Tail recursion
- Definition: function tail calls itself
- Function: as long as the use of tail recursion will not occur stack overflow, relatively save memory
- Implementation: rewrites all internal variables used as function arguments and uses parameter defaults
- The tail call
Error of arrow function
- Functional in vivo
this
isThe object where the definition is located
Rather thanThe object in which it is used
- Can let a
this
Points to immobilization, a feature that is useful for encapsulating callback functions - Not as a
The constructor
, so the arrow function is not availableThe new command
- Do not use
Yield command
, so the arrow function cannot be usedThe Generator function
- Do not use
The Arguments object
This object does not exist in the function body (available)Rest/spread parameters
Instead of) - An object must be returned in parentheses
Regular extension
- Change the RegExp constructor parameters: Allows the first parameter to be
Regular object
, tail parameter isRegular modifier
(The returned regular expression ignores the qualifier of the original regular expression.) - Regular method call changes: of string objects
match()
,replace()
,search()
,split()
Internal calls become callsRegExp
Instance correspondingThe RegExp. Prototype [Symbol. Methods]
- U modifier: Unicode schema modifier that handles properly greater than
\uFFFF
theUnicode characters
Some characters
(.).Unicode representation
quantifiers
Predefined pattern
The I modifier
escape
- Y modifier: adhesion modifier that ensures that matches must start with the first remaining position
G modifier
Similar effect) - unicode: Whether to set
U modifier
- sticky: Whether to set
Y modifier
- flags: Returns the modifier of a regular expression
The difficult
Y modifier
Implied header matching flag^
- Just one
Y modifier
rightmatch()
Only the first match must be returnedG modifier
All matches are returned in combination
Symbol
- Definition: unique value
- Statement:
const set = Symbol(str)
- Input parameter: string (optional)
- methods
- Symbol(): Creates an object described by parameters
Symbol value
(Not registered in the global environment) - Symbol.for(): Creates an object described by parameters
Symbol value
If this parameter exists, return the original oneSymbol value
(Search first, then create, register in global) - Symbol.keyFor(): Returns the registered
Symbol value
(can only be returnedSymbol.for()
thekey
) - Object.getOwnPropertySymbols(): returns all that are used as property names in an object
Symbol value
An array of
- Symbol(): Creates an object described by parameters
- built-in
- Symbol.hasInstance: points to an internal method that is used by other objects
The instanceof operator
This method is called to determine whether there is an instance of this object - Symbol.isConcatSpreadable: refers to a Boolean that defines an object for
Array.prototype.concat()
Can be expanded when - Symbol. Species: Refers to a constructor that is called when an instance object uses its own constructor
- Symbol.match: refers to a function when the instance object is
String.prototype.match()
It will be redefined when calledmatch()
The behavior of the - Symbol.replace: refers to a function when the instance object is
String.prototype.replace()
It will be redefined when calledreplace()
The behavior of the - Symbol.search: refers to a function when the instance object is
String.prototype.search()
It will be redefined when calledsearch()
The behavior of the - Symbol.split: refers to a function when the instance object is
String.prototype.split()
It will be redefined when calledsplit()
The behavior of the - Symbol.iterator: points to a default traverser method when the instance object executes
for-of
The specified default traverser is invoked - Symbol. ToPrimitive: Refers to a function that returns the primitive type value of an instance object when it is converted to that primitive type
- Symbol.toStringTag: refers to a function when the instance object is
Object.prototype.toString()
When called, the return value appears intoString()
The type of object is represented in the string returned - Symbol.unscopables: Points to an object, specifying the use of
with
Which properties will beWith the environment
To rule out
- Symbol.hasInstance: points to an internal method that is used by other objects
The data type
- Undefined
- Null
- String
- Number
- Boolean
- Object(including,
Array
,Function
,Date
,RegExp
,Error
) - Symbol
Application scenarios
- Unique object attribute names: Attribute names of type Symbol are unique and are guaranteed not to conflict with other attribute names
- Magic string: A specific string or number that occurs multiple times in code and is strongly coupled to the code
- Traversal attribute name: failed
for-in
,for-of
,Object.keys()
,Object.getOwnPropertyNames()
,JSON.stringify()
Return, only throughObject.getOwnPropertySymbols
return - Enable the Singleton pattern for modules: calling a class returns the same instance at any time (
window
andglobal
), usingSymbol.for()
To simulate the globalThe Singleton pattern
The difficult
Symbol()
A value that generates a primitive type is not an object, thereforeSymbol()
Not used beforeThe new command
Symbol()
Parameter indicates the currentSymbol value
With the same parametersSymbol()
Return values are not equalSymbol value
Cannot operate with values of other typesSymbol value
throughString()
ortoString()
Explicit conversion to a stringSymbol value
As an object property name, this property is a public property, but not a private propertySymbol value
As an object property name, you can only use the square bracket operator ([]
) without using the dot operator (.
Read)Symbol value
When used as an object property name, it is not traversed by a normal method and can be defined for an objectMethods that are not private but are used internally only
Set
Set
- Definition: A data structure, similar to an array, where member values are unique and have no duplicate values
- Statement:
const set = new Set(arr)
- Input parameter: Yes
The Iterator interface
Data structure of - attribute
- Constructor: constructor that returns a Set
- Size: Returns the total number of instance members
- methods
- Add () : Add the value and return the instance
- Delete () : deletes the value and returns a Boolean
- Has () : Checks the value and returns a Boolean
- Clear () : Clears all members
- Keys () : returns an object that traverses the property value
- Values () : Returns an object that traverses the property value
- Entries () : Returns objects with property values and property values as iterators
- ForEach () : Uses a callback function to iterate over each member
Application scenarios
- Deduplicate string:
[...new Set(str)].join("")
- Deduplicate arrays:
[...new Set(arr)]
orArray.from(new Set(arr))
- Set the array
- Statement:
const a = new Set(arr1)
,const b = new Set(arr2)
- And set:
new Set([...a, ...b])
- Intersection:
new Set([...a].filter(v => b.has(v)))
- Difference set:
new Set([...a].filter(v => ! b.has(v)))
- Statement:
- Map collections
- Statement:
let set = new Set(arr)
- Mapping:
set = new Set([...set].map(v => v * 2))
orset = new Set(Array.from(set, v => v * 2))
- Statement:
The difficult
- Traversal order: insertion order
- There’s no key, there’s only a value, and you can think of the key and the value as equal
- Add multiple
NaN
, only one will existNaN
- When the same object is added, it is thought to be a different object
- Casting does not occur when adding values (
5! = = "5"
) keys()
andvalues()
Is exactly the same,entries()
The returned iterator includes both the key and the value and the two values are equal
WeakSet
- Definition: Similar to the Set structure, member values can only be objects
- Statement:
const set = new WeakSet(arr)
- Input parameter: Yes
The Iterator interface
Data structure of - attribute
- Constructor: returns a WeakSet
- methods
- Add () : Add the value and return the instance
- Delete () : deletes the value and returns a Boolean
- Has () : Checks the value and returns a Boolean
Application scenarios
- Store DOM nodes: This member is automatically released when the DOM nodes are removed, without worrying about memory leaks when they are removed from the document
- Temporarily holds a group of objects or holds information bound to objects: as long as the objects disappear from the outside, it remains
WeakSet structure
Is automatically eliminated
The difficult
- Members are
A weak reference
, the garbage collection mechanism does not considerWeakSet structure
A reference to this member - Member is not suitable for reference, it will disappear at any time, so ES6 stipulates
The WeakSet structure is not traversable
- When other objects no longer reference the member, the garbage collection mechanism automatically reclaims the memory used by the member, regardless of whether the member still exists
WeakSet structure
In the
Map
Map
- Definition: An object-like data structure where a member key is a value of any type
- Statement:
const set = new Map(arr)
- Input parameter: Yes
The Iterator interface
And each member is a two-element array data structure - attribute
- Constructor: constructor that returns Map
- Size: Returns the total number of instance members
- methods
- Get () : returns a key-value pair
- Set () : adds a key-value pair and returns the instance
- Delete () : deletes the key-value pair and returns a Boolean
- Has () : Checks the key-value pair and returns a Boolean
- Clear () : Clears all members
- Keys () : returns the object traversed by the key
- Values () : Returns an object traversed by a value
- Entries () : returns objects traversed by keys and values
- ForEach () : Uses a callback function to iterate over each member
The difficult
- Traversal order: insertion order
- If you assign a value to the same key more than once, the later value overrides the previous one
- A reference to the same object is treated as a key
- Two instances of the same value are treated as two keys
- Keys are bound to memory addresses and are considered two keys as long as the memory addresses are different
- Add more than one
NaN
As a key, there will only be oneNaN
Value as a key The Object structure
provideString - value
The corresponding,Structure of the Map
provideValue -
The corresponding
WeakMap
- Definition: Similar to the Map structure, member keys can only be objects
- Statement:
const set = new WeakMap(arr)
- Input parameter: Yes
The Iterator interface
And each member is a two-element array data structure - attribute
- Constructor: returns a WeakMap
- methods
- Get () : returns a key-value pair
- Set () : adds a key-value pair and returns the instance
- Delete () : deletes the key-value pair and returns a Boolean
- Has () : Checks the key-value pair and returns a Boolean
Application scenarios
- Store DOM nodes: This member key is automatically released when the DOM nodes are removed without worrying about memory leaks when they are removed from the document
- Deploy private properties: Internal properties are weak references to the instance and disappear when the instance is deleted without causing a memory leak
The difficult
- Member keys are both
A weak reference
, the garbage collection mechanism does not considerWeakMap structure
A reference to this member key - The member key is not suitable for reference, it will disappear at any time, so ES6 states
The WeakMap structure is not traversable
- When other objects no longer reference the member key, the garbage collection mechanism automatically reclaims the memory used by the member, regardless of whether the member still exists
WeakMap structure
In the - Once the member is no longer needed, the member automatically disappears without manually deleting the reference
- Weak references
It's just the key, not the value
, the value is still a normal reference - Even if the reference to the member key is removed externally, the internal member value still exists
Proxy
- Definition: Modifies the default behavior of some operations
- Statement:
const proxy = new Proxy(target, handler)
- The ginseng
- Target: intercepts the target object
- Handler: custom interception behavior
- methods
- Proxy.revocable(): Returns a cancelable Proxy instance (returned
{ proxy, revoke }
Revoke ().)
- Proxy.revocable(): Returns a cancelable Proxy instance (returned
- Intercept way
- Get () : intercepts the reading of object properties
- Set () : intercepts object property Settings and returns a Boolean
- has(): Intercepts object property check
k in obj
To return to Bull - deleteProperty(): Intercepts object property deletion
delete obj[k]
To return to Bull - defineProperty(): Intercepts object property definitions
Object.defineProperty()
,Object.defineProperties()
To return to Bull - ownKeys(): Intercepts object property traversal
for-in
,Object.keys()
,Object.getOwnPropertyNames()
,Object.getOwnPropertySymbols()
, return an array - getOwnPropertyDescriptor(): Reads the property description of the intercepting object
Object.getOwnPropertyDescriptor()
, return object - getPrototypeOf(): Intercepts object prototype reads
instanceof
,Object.getPrototypeOf()
,Object.prototype.__proto__
,Object.prototype.isPrototypeOf()
,Reflect.getPrototypeOf()
, return object - setPrototypeOf(): Intercepts object prototype Settings
Object.setPrototypeOf()
To return to Bull - isExtensible(): Whether the intercepting object is extensible read
Object.isExtensible()
To return to Bull - preventExtensions(): Intercepts non-extensible Settings for objects
Object.preventExtensions()
To return to Bull - apply(): Intercepts Proxy instances as function calls
proxy()
,proxy.apply()
,proxy.call()
- construct(): Intercepts Proxy instance as constructor call
new proxy()
Application scenarios
Proxy.revocable()
: Do not allow direct access to the object, must be through the proxy access, once the access is finished, the proxy is withdrawn and no further access is allowedget()
: Error reading unknown attribute, read value of negative index of array, encapsulate chain operation, generate DOM nested nodeset()
: Data binding (implementation principle of Vue data binding). Ensures that the property value is set properly and prevents external access to the internal propertyhas()
: Hides internal attributes from discovery and excludes objects that do not meet attribute conditionsdeleteProperty()
: Protects internal properties from being deleteddefineProperty()
: prevents properties from being defined externallyownKeys()
: Protects internal properties from being traversed
The difficult
- To make the
Proxy
It works. It has to be targetedThe instance
To operate, not toThe target object
operate - When no interceptions are set, the same as
Directly to the original object
- Property is defined as
Cannot read/write/extend/configure/enumerate
An error will be reported when using the intercepting method - Target object under the proxy, internal
this
Point to theThe Proxy agent
Reflect
- Definition: keep
Object methods
Default behavior of - methods
- Get () : Returns object properties
- Set () : sets the object properties and returns a Boolean
- Has () : Checks object properties and returns a Boolean
- DeleteProperty () : deletes an object property and returns a Boolean
- DefineProperty () : Defines object properties and returns a Boolean
- ownKeys(): Iterates over the object properties, returning an array (
Object.getOwnPropertyNames()
+Object.getOwnPropertySymbols()
) - GetOwnPropertyDescriptor () : Returns an object property description
- GetPrototypeOf () : Returns the object prototype, returning the object
- SetPrototypeOf () : sets the object prototype and returns a Boolean
- IsExtensible () : returns whether the object isExtensible, returning a Boolean
- PreventExtensions () : Set object non – extensible, return Boolean
- Apply () : execute the specified function after binding this
- Construct () : Call the constructor to create the instance
Designed to
- will
Object
Belong toInternal language methods
In theReflect
on - Change some Object method error to return
false
- let
The Object operation
becomeFunction behavior
Proxy
withReflect
Complement each other
Abandoned method
Object.defineProperty()
= >Reflect.defineProperty()
Object.getOwnPropertyDescriptor()
= >Reflect.getOwnPropertyDescriptor()
The difficult
The Proxy method
andReflect method
One to one correspondenceProxy
andReflect
In combination, the former is responsibleIntercepts assignment operations
, who is responsible forThe assignment operation is complete
Data binding: Observer mode
const observerQueue = new Set(a);const observe = fn= > observerQueue.add(fn);
const observable = obj= > new Proxy(obj, {
set(tgt, key, val, receiver) {
const result = Reflect.set(tgt, key, val, receiver);
observerQueue.forEach(v= > v());
returnresult; }});const person = observable({ age: 25.name: "Yajun" });
const print = () = > console.log(`${person.name} is ${person.age} years old`);
observe(print);
person.name = "Joway";
Copy the code
Class
- Definition: An abstraction (constructor syntax sugar) of a class of things that have common characteristics
- Principle: The class itself points to the constructor, where all methods are defined
prototype
Can be viewed as another way of writing the constructor (Class === Class.prototype.constructor
) - Methods and keywords
- constructor(): constructor,
The new command
Automatically called when the instance is generated - Extends: extends the parent class
- super: of the new superclass
this
- Static: Defines static property methods
- Get: The value function that intercepts the value behavior of a property
- Set: a value saving function that intercepts the value saving behavior of a property
- constructor(): constructor,
- attribute
- __proto__:
Constructor inheritance
(Always pointing toThe parent class
) - __proto__.__proto__: the stereotype of the subclass’s stereotype, that is, the stereotype of the superclass (always pointing to the superclass)
__proto__
) - prototype.__proto__:
Inheritance of property methods
(always refer to the superclassprototype
)
- __proto__:
- Static properties: Properties that are assigned after a class is defined
It is not inherited by the instance
Can only be called by a class - Static methods: Use
static
Define the method, the methodIt is not inherited by the instance
Can only be called by a classthis
Pointing to a class, not an instance) - inheritance
- The essence
- ES5 essence: Create subclass instances first
this
, and then add the property method of the parent class tothis
(Parent.apply(this)
) - ES6 essence: first add the property method of the superclass instance to
this
(callsuper()
), and then modified with the subclass constructorthis
- ES5 essence: Create subclass instances first
- super
- Called as a function: Can only be called in a constructor
super()
Inside,this
inheritableThe current subclass
(super()
Called before it can be used in the constructorthis
) - Called as an object: in
Common methods
In the pointThe prototype object of the parent class
In theA static method
In the pointThe parent class
- Called as a function: Can only be called in a constructor
- Display definition: Use
constructor() { super(); }
Define inherited parent class, no written ruleAccording to defined
- Subclass inherits from parent class: When a subclass uses a property method of the parent class, it must be called in the constructor
super()
Otherwise you don’t get the superclassthis
- Static property methods of a parent class can be inherited by a child class
- After a subclass inherits from its parent class, it can
super
Calls the parent class static property method on
- The essence
- Instance: Class is equivalent to
Prototype of instance
All property methods defined in the class are inherited by the instance- Explicitly specify a property method: use
this
Specify on itself (useClass.hasOwnProperty()
Detectable) - Implicitly specify property methods: Declare definitions directly on object stereotypes (using
Class.__proto__.hasOwnProperty()
Detectable)
- Explicitly specify a property method: use
- expression
- Class expressions:
const Class = class {}
- Name attribute: Return immediately
class
After the name of the class - Attribute expression:
[prop]
- Methods the Generator:
* mothod() {}
- Async methods:
async mothod() {}
- Class expressions:
- This points to an error when an instance property or method is deconstructed
- Binding this:
this.mothod = this.mothod.bind(this)
- Arrow function:
this.mothod = () => this.mothod()
- Binding this:
- Attribute definition location
- Is defined in the constructor and uses
this
Point to the - Defined in the
Classes at the top
- Is defined in the constructor and uses
- New.target: Determine how the constructor is called
Native constructor
- String()
- Number()
- Boolean()
- Array()
- Object()
- Function()
- Date()
- RegExp()
- Error()
The difficult
- Calling a method on an instance is essentially calling a method on a prototype
Object.assign()
It is easy to add multiple methods to a class at once (Object.assign(Class.prototype, { ... })
)- All methods defined inside the class are non-enumerable (
non-enumerable
) - By default, the constructor returns an instance object (
this
), you can specify to return another object - The value and store functions are set on the property
Descriptor object
on - There is no variable promotion for the class
- using
new.target === Class
Write a class that cannot be used independently and can only be used after inheritance - After a child inherits from its parent,
this
Point to a subclass instance, throughsuper
If you assign a value to a property, the assigned property becomes a property of the subclass instance - use
super
You must explicitly specify whether to use it as a function or as an object extends
Inheriting not only the class but also the native constructor
Private property method
const name = Symbol("name");
const print = Symbol("print");
class Person {
constructor(age) {
this[name] = "Bruce";
this.age = age;
}
[print]() {
console.log(`The ${this[name]} is The ${this.age} years old`); }}Copy the code
Inherited hybrid class
function CopyProperties(target, source) {
for (const key of Reflect.ownKeys(source)) {
if(key ! = ="constructor"&& key ! = ="prototype"&& key ! = ="name") {
const desc = Object.getOwnPropertyDescriptor(source, key);
Object.defineProperty(target, key, desc); }}}function MixClass(. mixins) {
class Mix {
constructor() {
for (const mixin of mixins) {
CopyProperties(this.newmixin()); }}}for (const mixin of mixins) {
CopyProperties(Mix, mixin);
CopyProperties(Mix.prototype, mixin.prototype);
}
return Mix;
}
class Student extends MixClass(Person.Kid) {}
Copy the code
Module
- The command
- export: Specifies the external interface of the module
- The default is derived:
export default Person
(You can specify any module name when importing, without knowing the internal real name) - Separate export:
export const name = "Bruce"
- On-demand export:
export { age, name, sex }
(recommended) - Renamed the export:
export { name as newName }
- The default is derived:
- import: Imports internal module functions
- The default import:
import Person from "person"
- The overall import:
import * as Person from "person"
- According to the need to import:
import { age, name, sex } from "person"
- Renamed the import:
import { name as newName } from "person"
- Since the directed into the:
import "person"
- Composite import:
import Person, { name } from "person"
- The default import:
- Composite patterns:
The export command
andThe import command
The variables are not imported into the current module in essence, which is equivalent to the external forwarding interface. As a result, the current module cannot directly use its imported variables- Default Import and Export:
export { default } from "person"
- Overall import and Export:
export * from "person"
- Import and export as needed:
export { age, name, sex } from "person"
- Rename Import and Export:
export { name as newName } from "person"
- Change the name to default import and export:
export { name as default } from "person"
- The default value is named import and export:
export { default as name } from "person"
- Default Import and Export:
- export: Specifies the external interface of the module
- Inheritance:
The default is derived
andRenamed the export
In combination, modules can be inherited - Design idea: Make it as static as possible so that the dependencies of the module and the variables in and out of the module can be determined at compile time
- Strict mode: ES6 modules automatically adopt strict mode (whether the module header is added or not)
use strict
)
Modular solution
- CommonJS: for servers (dynamic dependencies)
- AMD: for browsers (dynamic dependency)
- CMD: for the browser (dynamic dependency)
- UMD: for browser and server (dynamic dependency)
- ESM: for browser and server (statically dependent)
Loading way
- Runtime loading
- Definition: the whole load module generates an object, then obtains the required properties and methods from the object to load (all load)
- Impact: This object is only available at runtime, making it impossible to do static optimization at compile time
- Compile time loading
- Definition: Load the required properties and methods directly from the module (load on demand)
- Impact: The module is loaded at compile time, which is more efficient than other schemes, but cannot reference the module itself (itself is not an object), can extend the JS advanced syntax (macros and type verification).
Loading implementation
- Traditional loadThrough:
<script>
Load the script synchronously or asynchronously- Synchronous loading:
<script src=""></script>
- Defer loads asynchronously:
<script src="" defer></script>
(Load sequentially and execute after rendering) - Async Asynchronous loading:
<script src="" async></script>
(Load out of order, download and execute)
- Synchronous loading:
- Module is loaded:
<script type="module" src=""></script>
(The default is Defer, loaded asynchronously)
CommonJS and ESM differences
CommonJS
The outputA copy of the value
.ESM
The outputThe value of the reference
CommonJS
Once a value is output, changes within the module cannot affect itESM
Is a dynamic reference and does not cache values. Variables in a module are bound to the module in which they are located, and when the script is actually executed, the value is evaluated based on this read-only reference to the loaded module
CommonJS
Is runtime loading,ESM
Is loaded at compile timeCommonJS
Load modules are objects (i.emodule.exports
), this object is generated only after the script has runESM
A load module is not an object, its external interface is just a static definition, which is generated during the static code parsing phase
The Node load
- Background:
CommonJS
andESM
Incompatible, the current solution is to separate the two and adopt their own loading scheme - Distinction: Requirements
ESM
using.mjs
Suffix file namerequire()
Cannot loadThe MJS file
, onlyThe import command
Can only be loadedThe MJS file
The MJS file
Cannot be used inrequire()
Must be usedThe import command
Load the file
- Driver:
node --experimental-modules file.mjs
- Restriction: Node
The import command
Currently, only local modules can be loaded (File: agreement
), the remote module is not supported - Load priority
- The script file omits the suffix: try loading the four suffix files in turn (
.mjs
,.js
,.json
,node
) - None: try to load
package.json
theThe main field
Specified script - None above: try to load the name as
index
Four file extensions (.mjs
,.js
,.json
,node
) - If the above does not exist, an error is reported
- The script file omits the suffix: try loading the four suffix files in turn (
- Non-existent internal variables:
arguments
,exports
,module
,require
,this
,__dirname
,__filename
- CommonJS load ESM
- You can’t use
require()
, can only be usedimport()
- You can’t use
- ESM load CommonJS
- automatically
module.exports
Converted intoexport default
CommonJS
The output caching mechanism is inESM
Still valid in load mode- using
The import command
loadingCommonJS module
Is not allowed to be usedAccording to the need to import
Should be used,The default import
orThe overall import
- automatically
Cyclic loading
- Definition:
A script
Execution dependency ofScript B
And theA script
The execution of theScript B
- Loading principle
- CommonJS:
require()
The first time the script is loaded, the entire script is executed, creating an object cache in memory, and the second time the script is loaded directly from the cache - ESM:
The import command
The load variable is not cached, but instead becomes a reference to the loaded module
- CommonJS:
- Cyclic loading
- CommonJS: Output only the parts that have been executed, not the parts that have not been executed
- ESM: Developers are required to ensure that the actual value can be obtained (variables can be written in the form of functions, functions can be promoted)
The difficult
- In the ES6 module, the top layer
this
Point to theundefined
Should not be used in top-level codethis
- A module is a separate file. All variables inside the file are not available externally
The export command
The output interface and its corresponding value areDynamic binding relationship
, that is, the real-time internal value of the module can be obtained through this interfaceThe import command
The variable name in the braces must be the same as the name of the external interface of the module being importedThe import command
The input variable is read-only (essentially the input interface) and cannot be overwritten in the script that loads the moduleThe import command
The command is promoted to the head of the entire module and is executed first- Repeat the same sentence
The import statement
Is executed only once export default
The command can be used only onceExport the default command
Export the whole module in executionThe import command
Can’t follow afterCurly braces
Export the default command
Essentially output a name calleddefault
Variable of, cannot be followed byVariable declaration statement
Export the default command
Essentially, assign the following value to the namedefault
And you can write the value directly after itExport the default command
andExport {} command
Can exist simultaneously, corresponding toComposite import
The export command
andThe import command
Can appear anywhere in a module, as long as it is at the top level of the module, not at block level scopeimport()
After the module is successfully loaded, the module is treated as an objectthen()
Can be usedObject to destruct assignment
To get the output interface- This parameter can be used when multiple modules are dynamically loaded at the same time
Promise.all()
andimport()
Combined to achieve import()
And in combination withasync/await
To write the code for synchronous operations
Singleton mode: cross-module constants
// Constants are shared across files
// person.js
const NAME = "Bruce";
const AGE = 25;
const SEX = "male";
export { AGE, NAME, SEX };
Copy the code
// file1.js
import { AGE } from "person";
console.log(AGE);
Copy the code
// file2.js
import { AGE, NAME, SEX } from "person";
console.log(AGE, NAME, SEX);
Copy the code
Default import swaps overall import
import Person from "person";
console.log(Person.AGE);
Copy the code
import * as Person from "person";
console.log(Person.default.AGE);
Copy the code
Iterator
- Definition: To provide a uniform access mechanism for various data structures
- How it works: Create a pointer to the first member and use it in order
next()
Points to the next member, directly to the end (data structures are only deployedThe Iterator interface
To complete the traversal operation) - role
- Provide a unified and simple access interface for various data structures
- Enables the data structure members to be arranged in some order
- ES6 creates new traversal commands
for-of
.The Iterator interface
Mainly used forfor-of
consumption
- Form:
for-of
(Automatically find the Iterator interface) - The data structure
- Collection:
Array
,Object
,Set
,Map
- Native data structures with interfaces:
String
,Array
,Set
,Map
,TypedArray
,Arguments
,NodeList
- Collection:
- Deployment: The default deployment is
Symbol.iterator
This attribute is consideredIterable
) - Iterator object
- next(): Next operation, return
{ done, value }
(Must be deployed) - return():
for-of
Exit the call early and return{ done: true }
- throw(): Do not use, cooperate
The Generator function
use
- next(): Next operation, return
ForOf cycle
- Definition: call
The Iterator interface
Generate a traverser object (for-of
Calling data structures internallySymbol.iterator()
) - Traversal string:
for-in
To obtainThe index
.for-of
To obtainvalue
(Recognizes 32-bit UTF-16 characters) - Traversing the number group:
for-in
To obtainThe index
.for-of
To obtainvalue
- Iterating over objects:
for-in
To obtainkey
.for-of
Deploy it on your own - Traverse the Set:
for-of
To obtainvalue
= >for (const v of set)
- Through the Map:
for-of
To obtainKey/value pair
= >for (const [k, v] of map)
- Iterating over an array of classes:
An object that contains length
,The Arguments object
,The NodeList object
(noAn array of classes for the Iterator interface
availableArray.from()
Translation) - Computationally generated data structures:
Array
,Set
,Map
- Keys () : returns a traverser object that traverses all keys
- Values () : Returns a traverser object that traverses all values
- Entries () : Returns an iterator object that iterates over all key-value pairs
- with
for-in
The difference between- With with
for-in
Same neat syntax, but nofor-in
Those shortcomings, - Different from the
forEach()
, it can be withbreak
,continue
andreturn
Together with - Provides a uniform operation interface for traversing all data structures
- With with
Application scenarios
- Rewriting has
The Iterator interface
Of the data structureSymbol.iterator
- Deconstruct assignment: Structure a Set
- Extension operator: will be deployed
The Iterator interface
Convert the data structure into an array - Yield * :
yield*
Followed by a traversable data structure, its traverser interface is called - Functions that take an array as an argument:
for-of
,Array.from()
,new Set()
,new WeakSet()
,new Map()
,new WeakMap()
,Promise.all()
,Promise.race()
Promise
- Definition: An object that contains the result of an asynchronous operation
- state
- ongoing:
pending
- Has been successfully:
resolved
- Has failed:
rejected
- ongoing:
- The characteristics of
- The state of an object is unaffected
- Once the state changes it doesn’t change again, it can happen any time
- Statement:
new Promise((resolve, reject) => {})
- The ginseng
- resolve: Changes the state from
unfinished
intosuccessful
Called when the asynchronous operation succeeds and passes the result of the asynchronous operation as a parameter - reject: Changes the state from
unfinished
intofailure
Called when the asynchronous operation fails and passes the error of the asynchronous operation as a parameter
- resolve: Changes the state from
- methods
- then(): specify separately
Resolved state
andRejected state
Callback function- The first parameter: The status changes to
resolved
Called when the - The second parameter: The status changes to
rejected
(Optional)
- The first parameter: The status changes to
- Catch () : Specifies the callback function when an error occurs
- Promise.all(): wrap multiple instances into a new instance and return an array of results after all instances have changed.
- Input parameter: Yes
The Iterator interface
Data structure of - Success: Only all instances become
fulfilled
The final state becomesfulfilled
- Failed: One of the instance states becomes
rejected
The final state is going to berejected
- Input parameter: Yes
- Promise.race(): wrap multiple instances into a new instance and return the result of all instance status changes (first changed, first returned)
- Input parameter: Yes
The Iterator interface
Data structure of - Success or failure: the state of the instance that changed state first is returned
- Input parameter: Yes
- Promise.resolve(): Converts an object to a Promise object (equivalent to
new Promise(resolve => resolve())
)- Promise instance: Returns the incoming argument intact
- Thenable object: Convert this object to a Promise object and return (Thenable for include
then()
Object to executethen()
Equivalent to executing this objectthen()
) - Objects that do not have then(): Converts this object to a Promise object and returns it with a state of
resolved
- With no arguments: Returns a Promise object in the state of
resolved
- Promise.reject(): converts an object to
rejected
Promise object (equivalent tonew Promise((resolve, reject) => reject())
)
- then(): specify separately
Application scenarios
- Loading pictures
- AJAX to a Promise object
The difficult
- Only the result of an asynchronous operation determines which state the current is; no other operation can change the state
- There are only two possible state changes: from
pending
intoresolved
And from thepending
intorejected
- Once the new
Promise object
It will be executed immediately. There is no way to cancel - With no callback function set, internal throws are not reflected externally
- When in
pending
It is impossible to know the current stage of progress - Instance status changes
resolved
orrejected
Is triggeredthen()
The bound callback function resolve()
andreject()
Always executes later than the synchronization task in this cyclethen()
Returns a new instance, after which another one can be calledthen()
then()
An error thrown during the run will becatch()
capturereject()
Is equivalent to throwing an error- The instance state has changed
resolved
The error is invalid and will not be caught - The instance state error has
The bubbling
Property, it’s passed back until it’s caught, and the error is always the next onecatch()
capture - Don’t in
then()
In the definitionrejected
State callback function (without its second argument) - It is recommended to use
catch()
Catch errors, do not usethen()
Second parameter capture - Don’t use
catch()
Error capture, instance throw error is not passed to the outer code, i.eThere will be no reaction
- The instance defined as a parameter
catch()
And once they arerejected
It doesn’t triggerPromise.all()
thecatch()
Promise.reject()
Is used as the argument forrejected
Becomes the argument to the subsequent method
Generator
- Definition: Asynchronous programming solution that encapsulates multiple internal states
- Form: call
The Generator function
(this function does not execute) Returns a pointer object to the internal state (not the run result) - Statement:
function* Func() {}
- methods
- next(): moves the pointer to the next state and returns
{ done, value }
(Admission is treated as the lastYield command expression
Return value of) - return(): Returns the specified value and terminates the traversal
The Generator function
To return to{done: true, value: value}
- throw()In:
The Generator function
Body throw error inThe Generator function
Error capture in body and return customnew Errow()
- next(): moves the pointer to the next state and returns
- Yield command: declare the value of internal state (
return
The value returned at the end of the declaration)- encounter
Yield command
Suspend the subsequent operation and take the value of the subsequent expression as the return object’svalue
- Next time you call
next()
The execution continues until the next one is encounteredYield command
- No more encounter
Yield command
I’m going to run all the way toThe Generator function
End, until meetReturn statement
And the value of the following expression as the return objectvalue
The Generator function
There is noReturn statement
Returns the object’svalue
forundefined
- encounter
- Yield * command: in a
The Generator function
To execute the otherThe Generator function
(Followed byThe Iterator interface
Data structure) - Traversal: Through
for-of
Automatically callnext()
- As an object property
- All write:
const obj = { method: function*() {} }
- Abbreviations:
const obj = { * method() {} }
- All write:
- Context: Produced by execution
Context
Once meetYield command
It will temporarily exit the stack (but not disappear), and all variables and objects will be frozen inThe current state
And wait until it is executednext()
When theContext
The call stack is added again, and the frozen variables and objects resume execution
Methods the similarities and differences
- Similarities:
next()
,throw()
,return()
It’s essentially the same thing, all it does is restore the function and replace it with a different statementYield command
- The difference between
- next()Will:
Yield command
Replace it with avalue
- return()Will:
Yield command
Replace it with aReturn statement
- throw()Will:
Yield command
Replace it with aThrow statement
- next()Will:
Application scenarios
- Asynchronous operations are expressed synchronously
- Control flow management
- Deploy the Iterator interface for the object: put
The Generator function
Assigned to an objectSymbol.iterator
, so that the object hasThe Iterator interface
- As a data structure with an Iterator interface
The difficult
- Each call
next()
The pointer goes fromFunction of the head
orWhere we stopped last time
Start execution until the next one is encounteredYield command
orReturn statement
So far, - Not inside the function
Yield command
But it will become simpleSuspended function
(Still neednext()
Trigger) Yield command
Is the flag that suspends execution,next()
Is to restore the operation performedYield command
To use in another expression must be placed inparentheses
In theYield command
Used as a function argument or to the right of an assignment expressionparentheses
Yield command
If there is no return value of its own, it is considered a returnundefined
Yield command expression
Evaluate for inertia, etcnext()
This is where the evaluation takes place- Function is called to generate a traverser object
Symbol.iterator
Is the object itself - At various stages of function operation, through
next()
Inject different values from the outside to the inside to adjust function behavior - One of the first
next()
Used to start the traverser object and pass parameters later - Want to call for the first time
next()
You can put in a value, and you can wrap it around the function - Once the
next()
Return object’sdone
fortrue
.for-of
The traversal is aborted and does not include the returned object - Function internal deployment
try-finally
And being executedtry
, thenreturn()
Will result in immediate entryfinally
, the implementation of thefinally
And then the whole thing ends - The function is not deployed internally
try-catch
.throw()
Throwing errors will be externaltry-catch
capture throw()
Throw error to be caught internally, the premise must beExecute next() at least once
throw()
Once captured, the next item is executed with itYield command
- The function has not yet been executed
throw()
A throw can only be thrown outside the function
The first time next() passes a value
function Wrapper(func) {
return function(. args) {
constgenerator = func(... args); generator.next();returngenerator; }}const print = Wrapper(function* () {
console.log(`First Input: The ${yield}`);
return "done";
});
print().next("hello");
Copy the code
ES2016
Numerical extension
- Exponent operator (**): Numerical exponentiation (equivalent to
Math.pow()
)
Array extension
- includes(): Indicates whether the specified member exists
ES2017
The statement
- Shared memory and atomic operations: is a global object
SharedArrayBuffer
andAtomics
To store the data in a shared memory spaceJS, the main thread
andWeb - worker thread
Shared between
String extension
- padStart(): Populates the specified string to the header of the string and returns the new string
- padEnd(): Populates the specified string to the end of the string and returns the new string
Object extension
- Object.getOwnPropertyDescriptors(): Returns a description object for all of the object’s own properties (non-inherited properties)
- Object.values(): Returns an array of values
- Object.entries(): Returns an array of keys and values
Function extension
- Function arguments end with a comma: Allows a trailing comma for the last argument of a function
Async
- Definition: Write an asynchronous function as a synchronous function (Generator function syntax sugar)
- Principle:
The Generator function
And the automatic actuatorspawn
Wrapped in a function - Form:
The Generator function
the*
replaceasync
That will beyield
replaceawait
- The statement
- Named function:
async function Func() {}
- Function expression:
const func = async function() {}
- Arrow function:
const func = async() => {}
- Object methods:
const obj = { async func() {} }
- Methods:
class Cla { async Func() {} }
- Named function:
- Await command: waits for the current Promise object to complete its state change
- Normal: Return the result if the Promise object is followed, otherwise return the corresponding value
- After the
Thenable object
: equates it to a Promise object returning its result
- Error handling: will
Await commands Promise objects
In thetry-catch
(can put more than one)
Async improves on Generator
- Built-in actuator
- Better semantics
- Wider applicability
- The return value is a Promise object
Application scenarios
- Complete asynchronous operations in sequence
The difficult
Async function
returnPromise object
, you can usethen()
Add a callback function- internal
Return the return value
Will be the nextthen()
Out of the cords - An internal throw error causes the Promise object returned to be
Rejected state
,catch()
To receive - The returned Promise object must wait for internal ownership
Await commands Promise objects
A state change does not occur until the execution is complete, unless encounteredReturn statement
orThrow an error
- Any one
Await commands Promise objects
intoRejected state
And the wholeAsync function
Will interrupt execution - It is expected that subsequent asynchronous operations will not be interrupted even if the previous asynchronous operation fails
- will
Await commands Promise objects
In thetry-catch
In the Await commands Promise objects
With acatch()
- will
Await commands Promise objects
May becomeRejected state
It’s better to put it intry-catch
In the- multiple
Await commands Promise objects
If there is no secondary relationship, it is best to let them both trigger together Await orders
Can only be used inAsync function
Otherwise, an error will be reported- Using an array
forEach()
performasync/await
It’s not working. It’s workingfor-of
andPromise.all()
Instead of - The run stack can be preserved with the function context
Async function
The execution exists and disappears when the execution is complete
ES2018
String extension
- Relax the restrictions on string escaping in tag templates: Returns an invalid string escape
undefined
And from theraw
To get the original string
Object extension
- Extension operator (…): converts an object to a comma-separated sequence of arguments (
{ ...obj }
, which is equivalent toRest/spread parameters
The inverse of
Extended application
- Clone object:
const obj = { __proto__: Object.getPrototypeOf(obj1), ... obj1 }
- Merge objects:
const obj = { ... obj1, ... obj2 }
- Convert a string to an object:
{ ..."hello" }
- Convert an array to an object:
{... } [1, 2]
- Combined with object destruct assignment:
const { x, ... rest/spread } = { x: 1, y: 2, z: 3 }
(Cannot copy properties inherited from prototype objects) - Modify some properties of an existing object:
const obj = { x: 1, ... { x: 2 } }
Regular extension
- S modifier: dotAll pattern modifier to enable
.
Match any single character (DotAll mode
) - dotAll: Whether to set
S modifier
- After assertion:
x
Only in they
After the match - A negative assertion follows:
x
Not onlyy
After the match - Unicode property escape: Match match
Unicode certain properties
All characters of- Forward matching:
\p{PropRule}
- Reverse matching:
\P{PropRule}
- Limitations:
\p{... }
and\P{... }
Only toUnicode characters
Effective, need to add when usingU modifier
- Forward matching:
- Named group matching: specifies a name for each group of matches (
? <GroupName>
)- Form:
str.exec().groups.GroupName
- Deconstruct assignment substitution
- Statement:
const time = "2017-09-11"
,const regexp = /(? <year>\d{4})-(? <month>\d{2})-(? <day>\d{2})/u
- Match:
time.replace(regexp, "$<day>/$<month>/$<year>")
- Statement:
- Form:
Promise
- finally(): Specifies a callback function that will be executed regardless of the final state
Async
- Asynchronous iterators (for-await-of): loop waiting for each
Promise object
intoResolved state
Before we go to the next step.
ES2019
String extension
- Enter U+2028 and U+2029 directly: A string that can be entered directly
Line separators
andParagraph delimiter
- JSON. Stringify (): Can return a string that does not meet the UTF-8 standard
- trimStart(): Removes Spaces from the string header and returns a new string
- trimEnd(): Removes trailing Spaces and returns a new string
Object extension
- Object.fromEntries(): returns an object consisting of keys and values (
Object.entries()
The inverse operation of)
Array extension
- Sort () stability: The sorting order of items with the same keywords does not change. The default is
stable
- flat(): flattens the array and returns the new array
- flatMap(): Maps and flattens an array, returning a new array (can only expand one level of an array)
Function extension
- The toString (): Returns the original code of the function (consistent with the code)
- The catch() argument can be omitted:
catch()
The parameters in can be omitted
Symbol
- descriptionReturns the
Symbol value
A description of the
ES2020
The statement
- globalThis: as a top-level object, pointing to the global environment
this
- Browser: The top-level object is
window
- Node: The top-level object is
global
- WebWorker: The top-level object is
self
- The above three: the generic top-level object is
globalThis
- Browser: The top-level object is
Numerical extension
- BigInt: any bit integer (new data type, use
n
At the end)- BigInt() : Converts an ordinary value to BigInt
- Bigint.asuintn () : Translates BigInt to a value corresponding between 0 and 2n-1
- Bigint.asintn () : Converts BigInt to -2n-1 to 2n-1-1
- BigInt.parseInt(): similar to
Number.parseInt()
Converts a string to a BigInt in the specified base
The difficult
- BigInt can also be expressed in a variety of bases, all with suffixes
- BigInt and ordinary integer are two values, and they are not equal
- The Typeof operator returns data of type BigInt
bigint
Object extension
- The chain determination operator (? .).: whether an object property exists (returns if no
undefined
And no further execution)- Object properties:
obj? .prop
,obj? .[expr]
- Function call:
func? . (... args)
- Object properties:
- The null judgment operator (??): Indicates whether the value is
undefined
ornull
If yes, the default value is used
Regular extension
- matchAll(): returns all matching iterators
Module
- import(): Dynamic import (returned
Promise
)- Background:
The import command
It is statically analyzed by the JS engine, executed before other statements in the module, and cannot be replacedrequire()
The dynamic loading function is proposed to be introducedimport()
To take the place ofrequire()
- Location: Can be used anywhere
- The difference between:
require()
isSynchronous loading.import()
isAsynchronous loading - Scenarios: Load on demand, conditional load, and dynamic module path
- Background:
Iterator
- For-in traversal order: Have the different engines agreed on how to iterate properties to standardize behavior
Promise
- Promise.allSettled(): wrap multiple instances into a new instance and return an array of state changes for all instances.
- Input parameter: Yes
The Iterator interface
Data structure of - Success: The member is included
status
andvalue
.status
forfulfilled
.value
For the return value - Failed: Member contains
status
andreason
.status
forrejected
.value
For error reasons
- Input parameter: Yes
ES proposal
The statement
- Do expression: Encapsulates a block-level scoped operation, returning the value of the last internal expression executed (
do{}
) - Throw expression: Direct use
throw new Error()
without(a)
or{}
including - ! # command: Specifies the script executor (written at the beginning of the file)
Numerical extension
- Numeric separator (_)Use:
_
As a thousandth separator (to increase the readability of the value) - Math.signbit(): Returns whether the value symbol is set
Function extension
- Function partial execution: Reuse function function (
?
Represents a single parameter placeholder,.
Represents multiple parameter placeholders) - The pipe operator (| >): Pass the value of the left expression to the right function for evaluation (
f(x)
= >x |> f
) - The binding operator (::): Function binding (object on the left and function on the right, replace
bind
,apply
,call
Call)- The bind:
bar.bind(foo)
= >foo::bar
- Apply:
bar.apply(foo, arguments)
= >foo::bar(... arguments)
- The bind:
Realm
- Definition: to provide
The sandbox function
, which allows code to be isolated and prevents the isolated code from getting the global object - Statement:
new Realm().global
Class
- Static attributesUse:
static
Define a property, the propertyIt is not inherited by the instance
Can only be called by a class - Private propertyUse:
#
Defines a property that can only be accessed within the class - Private methodsUse:
#
Defines a method that can only be accessed inside a class - A decoratorUse:
@
Annotate or modify classes and class methods
Module
- import.meta: Returns script meta information
Promise
- Promise.any(): wrap multiple instances into a new instance and return an array of results after all instances have changed.
- Input parameter: Yes
The Iterator interface
Data structure of - Success: One of the instance states becomes
fulfilled
The final state is going to befulfilled
- Failed: Only all instances have state changes
rejected
The final state becomesrejected
- Input parameter: Yes
- Promise.try(): does not want to distinguish between synchronous and asynchronous functions, wrapping functions as instances, using
then()
Specifies the next process, usingcatch()
Capture the error
Async
- The top Await: allows independent use at the top level of a module
Await orders
, to borrowawait
Solve the problem of asynchronous module loading)
conclusion
Finally, I will send you a complete ES6 feature map, remember to give me a like oh, it is a kind of encouragement to me. Because the picture is too big to upload, please pay attention to IQ front end or scan the bottom of the article TWO-DIMENSIONAL code, background reply ES6, get high-definition ES6 all features memory map, help you easily remember all features of ES6.
conclusion
❤️ follow + like + collect + comment + forward ❤️, original is not easy, encourage the author to create more high-quality articles
Follow the public accountIQ front-end
, a focus on CSS/JS development skills of the front-end public number, more front-end small dry goods waiting for you oh
- Follow and reply
data
Free access to study materials - Follow and reply
Into the group of
Pull you into the tech group - Welcome to attention
IQ front-end
And moreCSS/JS development skillsOnly in the public account push