This series contains all 28 chapters of the ES2021 specification. It is published in two installments. This installment contains the first 21 chapters and the rest are in the COMPLETE ES2021 Features (2).

preface

ES2021 is the 2021 version of the ECMAScript Language Specification (also known as the JS specification or ECMA-262), and is the twelfth version.

Some of these features are implemented differently in different browsers. For browser implementations, see Caniuse. To use the latest features, use Babel (see how Babel solved our problem for more on Babel).

This specification was written by the Ecma International Technical Committee 39, also known as TC39, and is the authoritative specification for all kinds of JS implementations, whether on the browser side or in Node.js, or whatever. All JS engine developers need to ensure that the features specified in the specification are implemented. By reading this specification, we can accomplish several goals

  • Overall grasp of the current version of ES standard, the construction of knowledge framework
  • When in doubt about the details of the JS runtime, for example, when I am sorting out the free element pattern of the design specification, I want to know which side to evaluate first when comparing two expressions.

If you want to read the original text of the specification, first-time readers may find it difficult to read it. Please refer to the following two reading guidelines:

  • Understanding ECMAScript
  • How to Read the ECMAScript Specification

The purpose of this article is to learn the language through the specification, so it focuses on the parts related to application, and there will be some trade-offs for implementation, most of which will be consistent with the original text. And the correlation between the weak can be selective reading

Start of the text πŸ‘Š

introduce

This section covers historical versions of the JS specification. For a more detailed introduction, please refer to the 20 Years of JavaScript co-written by Brendan Eich, the father of JavaScript, and Allen Wirfs-Brock, the lead author of the ES6 specification.

ES is based on a number of technologies, most notably JavaScript (Netscape) and JScript (Microsoft), a language invented by Brendan Eich at Netscape and first introduced in Navigator 2.0 Browser.

Development of the ES language specification began in November 1996. The first version was approved at the Ecma Conference in June 1997. The difference between version 2 and version 1 in June 1998 is the editorial.

Version 3 introduced regular expressions, enhanced string handling and new control statements, try/catch error capture, more rigorous error definition, formatting of digital output, and more, and was released in December 1999.

After release 3, ES gained widespread adoption along with the World Wide Web, which has become a programming language supported by virtually all Web browsers. The amount of work that went into developing release 4. However, this work is not yet complete and has not been released as version 4 of ES, but some of it has been incorporated into the development of version 6.

Version 5, released in December 2009, includes programmatic control of accessor attributes, reflection, new array manipulation functions, support for JSON objects, and stricter error checking and strict schemas. The 5.1 release of June 2011 contains some minor changes. πŸ‘΄

Version 6 began exactly as version 3 was released and took 15 years to complete in 2015. The goal is better support for large applications, library creation, and target languages compiled as other languages. The main enhancements include modules, class declarations, block scope, iterators, generators and promises for asynchronous programming, destruct patterns, and tail-call optimization. The built-in library supports additional data abstractions including maps, sets, and binary value arrays, as well as unicode support for complementary characters in strings and regular expressions. Built-in functions can also be extended by subclasses.

From 2016, ES started the annual iteration rhythm. ES2016 revised the bugs of the previous version and made other improvements, and developed several auxiliary software tools for this purpose, including Ecmarkup, Ecmarkdown, and Grammarkdow. Several power operators have also been added and an array. prototype method named includes has been added.

ES2017 introduces enhancements to Async functions, shared memory, Atomics, and smaller languages and libraries. Async functions enhance the asynchronous programming experience by providing syntax that returns promises. Shared memory and Atomics introduced the memory model to allow multi-agent programs to communicate through atomic operations to ensure sequential execution even on parallel cpus. Also added a new static method on the Object: the Object. The values of the Object. The entries, and the Object. GetOwnPropertyDescriptors.

ES2018 introduces support for asynchronous iteration through the Asynchronous Iteration protocol and asynchronous Generator, and also introduces four new features for regular expressions: dotAll tags, named capture groups, Unicode attribute escape, and backward assertion. Finally, there are the object REST and spread properties.

ES2019 introduces new built-in functions: Array.prototype adds flatandflatMap to flat the Array, while Object.fromEntries restores the value returned by Object.entries to a new Object. Will be widely implemented but non-standard String. The prototype, trimLeft and a good name trimRight trimStart and trimEnd. Other syntax updates include the optional catch argument, which allows the use of U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) to align JSON in strings. Demands array sort sorting stability, JSON. Stringify to return regardless of input format correct utf-8, back to the corresponding original source text by clear requirements or standard placeholder for the Function. The prototype. ToString.

ES2020 introduces the matchAll method for strings to generate iterators for all matching objects generated by global regular expressions; Import (), an asynchronous import module syntax; BigInt, an integer primitive type of arbitrary precision; Promise. AllSettled, a new Promise combo that doesn’t take shortcuts; GlobalThis is a generic way to access this; Export * as ns from ‘module’; Added standardization of for-in enumeration order; Import.meta, one that contains module context information for use in modules; And add two syntax features for null and undefined: nullish coalescing (?? , for value selection) and optional chaining (i.e.? . For short-circuiting possible NULL or undefined).

Range of 1.

The standard defines the ES 2021 general-purpose programming language.

2. The consistency

A standards-compliant ES implementation must support all types, values, objects, attributes, functions, and programming syntax semantics, and must interpret text input in accordance with the latest Unicode Standard and ISO/IEC 10646.

Nothing else.

3. Reference specifications

A reference specification is also required to implement this specification

  • Universal multi-octet coded character set UCS
  • International API standard ECMA-402
  • JSON data exchange format ecMA-404

Summary of 4.

Originally designed as a scripting language, ES is now widely used as a general-purpose programming language. The corresponding runtime environment (such as Node.js) should not only implement the objects and capabilities defined in the specification, but also have environment-specific features, such as input and output, timers, etc.

ES is object-based: the basic language and hosting capabilities are provided by objects, and an ES program is a set of objects that can communicate. In ES an object is a collection of zero or more properties. Each property has attributes that determine how each property is used. For example, when a property’s Writable property is set to false, it cannot be reassigned. Properties are containers that can contain other objects, primitive values, or functions. ES contains primitive values of the following seven built-in types: Undefined, Null, Boolean, Number, BigInt, String, and Symbol. An Object is a member of the built-in type Object, and functions are callable objects.

ES defines a set of built-in objects, These include global objects, basic language runtime semantic objects (object, Function, Boolean, Symbol, and different Error objects), objects used to represent and manipulate numeric values (Math, Number, And Date), text processing objects (String and RegExp), indexable objects (Array and different Typed Arrays), Keyed sets (Map and Set), JSON objects that support structured data, ArrayBuffer, SharedArrayBuffer, and DataView), Control abstraction objects (Generator functions and Promises), and Proxy and Reflect.

A series of built-in operators are also defined, including various unary operators, multiplication operators, addition operators, displacement operators, relational operators, equality operators, binary operators, binary logic operators, assignment operators, and comma operators

A module can divide a program into statements and declarations, with each module explicitly identifying the declarations provided by other modules it uses and which declarations are available to other modules.

The ES syntax is intentionally similar to the Java syntax, but is loose enough to make it an easy-to-use scripting language. Variables, for example, do not require type declarations.

Object

Although ES contains the syntax for class, it is not class-based like C++. Objects can be created in many ways, such as literals or constructors. Each constructor is a function with a Prototype property that implements Prototype-based inheritance and property sharing. To use a constructor with new, the result of not using new depends on the constructor itself. Each object created through the constructor has an implicit reference to the constructor’s Prototype property (called the object’s prototype and represented by __proto__), a prototype may also have a non-null __proto__, and so on, This is known as the Prototype Chain (see JavaScript Prototype and Prototype Chain explained or something I learned from exploring function.proto === function.prototype). Such as

var Foo=function(){}
var foo=new Foo()
foo.__proto__===Foo.prototype//true
foo.constructor===Foo //true
Copy the code

There are two special objects in the JS world, Object Funciton and Obejct. The prototype is all normal Object (not including directly through the Object. The create (null) and through setPrototypeOf explicitly created by the modified part Object) at the end of the prototype chain (Obejct. Prototyp E.__proto__ = null), including function.prototype, i.e

Function.prototype.__proto__===Object.prototype //true
new Object().__proto__===Object.prototype //true
Copy the code

Prototype, including Object and other built-in instantiable objects (such as Array), will need to pass through Function. Prototype before reaching Obejct. Prototype. And directly instantiated functions (such as Foo), and even Function itself

Foo.__proto__===Function.prototype //true
Object.__proto__===Function.prototype//true
Array.__proto__===Function.prototype//true
Function.__proto__===Function.prototype//true
Copy the code

In this way, you can extend the chain of prototypes by inheriting various subclasses based on the objects closest to the JS implementation, and this is what prototype inheritance is supposed to look like.

Strict mode

Strict mode provides js with the option of a strict variant, whose syntax and runtime behavior are different from normal code, and a browser that does not support strict mode will behave differently than a browser that does support strict mode. Strict mode has the following changes from normal JS

  • Convert acceptable errors to errors, such as trying to delete attributes that cannot be deleted
  • Fixed issues that made the JS engine difficult to optimize, such as the use of eval
  • Only syntax that may be defined in future versions is used, such as the addition of reserved keywords.

For details about the changes, see Strict Mode

Turn on strict mode

Strict mode can be applied to entire scripts or individual functions, but not to block scopes.

  • Turn on strict mode for the script

Add “use strict” before other statements; (or ‘use strict’;)

// Whole-script strict mode syntax 'use strict'; var v = "Hi! I'm a strict mode script!" ;Copy the code
  • Turn on strict mode for functions

Will “use strict”; Complete before a function body statement, such as

Function strict() {// function level strict mode syntax 'use strict'; function nested() { return "And so am I!" ; } return "Hi! I'm a strict mode function! " + nested(); } function notStrict() { return "I'm not strict."; }Copy the code
  • Set strict mode for modules

The entire content of a module defaults to strict mode

The structure of this specification

Chapter 5 defines the symbolic conventions of this specification, chapters 6 through 9 define the execution environment for THE ES program, chapters 10 through 16 define the syntactic encoding and execution semantics for language features, and chapters 17 through 27 define the ES library. Chapter 28 describes the memory consistency model and atomic object methods that support memory access to SharedArrayBuffer

5. Symbolic conventions

Here are some of the conventions that will be used in this specification and only the concepts that will be covered later

  • Parse Node: Source code is parsed into a tree, and each Node in the tree is a Parse Node.

6. ES data type and value

Each value we operate on in this specification has a type, and the possible types are defined in this chapter. The types are subdivided into ES language types and specification types, where the language types correspond to values directly operated on in ES programs. Specification type values are used in the implementation of ES to describe various raw or intermediate results that are not exposed to the language users.

Language type

Includes seven primitive value types and Object

Undefined

There is only one value, undefined, and any variable that is not assigned a value has undefined

Null

There is also only one value, null, which indicates that the variable does not point to any object. Null can be treated as an object that has not yet been created.

Boolean

Represents a logical entity with two values false and true

String

An ordered sequence of zero or more (up to 2^53-1, array length up to 2^32-1) 16-bit unsigned INTEGER, usually used to represent text data in a program. Each element in the sequence is treated as a UTF-16 and occupies a position indexed by a non-negative integer. The first element has an index of 0, and the empty sequence has no elements.

Symbol

Each Symbol value is unique and immutable and can be used as the property name of the object.

Number

The number types in ES are double precision IEEE754 64-bit floating point types,

  • Digit character (S,sign) 1 bit, indicating positive and negative, 0 is positive and 1 is negative
  • The 11-bit E,exponent represents the number of digits offset by the decimal point. The actual value used is equal to the exponent – bias value.
  • Mantissa (M,Mantissa)52 digits, representing the fractional part of a number

When E is not all 0 or 1 is an ordinary value, the highest mantissa digit has a default 1, which can be expressed as

precision

Accuracy is affected by mantissa and Number character, where the mantissa 52 bits, plus the default 1 of the highest bit, a total of 53 bits, that is, the accurate representation range of the integer is Β±2^53-1, in JS called safe integer (number.min_safe_INTEGER, number.max_safe_INTEGER), The maximum accuracy is 16 bits of the safe integer (9007199254740991).

Digital range

The order range is [βˆ’1022, 1023], when the absolute value is the largest, the mantissa are all 1 (approximately equal to 2), resulting in 2^1023*2, i.e. 2^1024. In JS, the value is represented by number. MAX_VALUE, and the value exceeding this value is represented by Infinity, and the mantissa are all 0 (equal to 1). Have 2 ^ (1022). But if you take the following nonnormalized number, the highest mantissa defaults to 0, that is, the decimal point is moved 52 places back. MIN_VALUE =2^(-1022-52)=2^(-1074).MIN_VALUE = 0. That may eventually said Numbers in the range of [2 ^ 1024-2 ^ (1074)] βˆͺ [2 ^ (1074), 2 ^ 1024].

Special values

  • When E is all 0, M is not all 0, the highest mantissa defaults to 0, indicating the normalized number
  • When E is all 0 and M is all 0, it means plus or minus 0
  • Infinite plus or minus infinity when E is all one and mantissa is all zero
  • NaN(not a number) = NaN(not a number)

BigInt

Represents an integer with no precision limitation

Object

An object is a collection of properties, each of which is either a data property or an accessor property.

  • Data attributes associate a key with a value of the ES language type, as well as a set of Boolean properties
  • Accessor properties associate a key with one or two accessor functions, as well as a set of Boolean properties. The accessor function is used to save or retrieve the ES value associated with this property

Attributes are marked with a key value. The key of an attribute is either a string or symbol. The key attribute is used to access attributes and other values. There are two ways to access attributes: get and set, for obtaining and assigning, respectively.

Properties of attributes

Properties are used in this specification to define and explain the state of an object property. A key associated with a data property has the following properties

  • [[value]] Any ES language type value that is obtained by GET
  • [[writable]] Boolean value, whether it can be modified
  • [[Enumerable]] is a Boolean value that can be usedfor-inThe enumeration
  • The [[64x]] 6464x works without additional control, without any additional information, and without additional control. The [[64X]] 64x works without additional control.

Accessor-property-related keys have the following properties

  • [[Get]] Obejct or undefined, if an object must be a function object, the function will be called every time the property is accessed
  • [[Set]] Object or undefined, if it is an Object it must be a function Object
  • [[Enumerable]] is a Boolean value that can be usedfor-inThe enumeration
  • [[64x]] Specifies the Boolean value of [[64X], which can be deleted or modified as a data attribute or modified feature
Object Internal Methods and Internal Slots

All objects are logically collections of properties, but there are many forms of objects that access and manipulate properties in different ways. In ES, the actual meaning of objects is realized by calling specific internal methods. In the ES engine, each object is associated with internal methods that define their runtime behavior. These internal methods are not part of the ES language, but are here for illustration only. But there must be representations of internal methods within the implementation. Internal method names are polymorphic, which means that different objects calling internal methods may behave differently. The internal slots correspond to the internal state of the object and are used for different ES specification algorithms. Internal slots are not object properties that cannot be inherited. Depending on the particular internal slot, these states may contain values of any ES language type or a specific ES specification type, which defaults to undefined. The ES language does not specify a direct way to access these internal slots.

Internal methods and internal slots are surrounded in the specification by double parentheses [[]].

Objects are divided into two categories, one is ordinary object, they meet the following criteria

  • For the following internal methods
    • [[GetPrototypeOf]] () - > Object | NullGet the inherited object, which is __proto__
    • [[SetPrototypeOf]] (Object | Null) - > BooleanSets the inherited object
    • [[IsExtensible]] () - > BooleanDetermines whether to allow attributes to be added
    • [[PreventExtensions]] () - > BooleanSet to not add attributes
    • [[GetOwnProperty]] (propertyKey) - > Undefined | Property DescriptorReturns its own property accessor
    • [[DefineOwnProperty]] (propertyKey PropertyDescriptor) - > BooleanCreates or modifies a property, where propertyKey is the propertyKey
    • [[HasProperty]] (propertyKey) - > BooleanDetermines whether it has itself or inherits the specified property
    • [[Get]] (propertyKey, Receiver), any)Returns the specified property
    • [[Set]] (propertyKey, value, Receiver) β†’ BooleanSet properties
    • [[Delete]] (propertyKey) - > BooleanDelete the properties
    • [[OwnPropertyKeys]] () β†’ List of propertyKeyReturns a LIST of all attributes of the object
  • If there are [[Call]] internal methods
    • [[Call]] (any, a List of any) β†’ anyA function object is an object with [[Call]] internal methods that are executed on Call
  • If there are [[Construct]] internal methods
    • [[Construct]] (a List of any, Object) β†’ ObjectA constructor that supports [[Construct]] must support [[Call]], i.e. a constructor must be a function that is executed when new or super is called

If they do not, they are Exotic objects. In the specification, different objects are identified through their own internal methods.

Given the internal object

Intrinsic objects are known to be built-in objects that are explicitly referenced by the algorithms in this specification, usually with the mark of a particular realm. An Intrinsic object is represented by %name%, as shown in Table 8: Well-known Intrinsic Objects.

ES specification types

Canonical types are used in algorithms to describe ES constructs and ES type meta-values. Here are some of the types covered in this article.

List

The list type is used to describe the values of argument lists in new expressions, function calls, and other algorithms that require simple ordered lists

Record

Used to describe a collection of data in an algorithm, a value of type Record contains one or more named fields, each of which is either an ES value or a Record. [[Writable]]: false, [[Writable]]: true}, [[64x]: 64x}, [[64X]: 64X}

Completion Record

Is a Record that describes runtime propagation of values and control flows such as break, continue, return and throw. The value of the Completion type is Record, and their fields are defined below

  • [[Type]] one of normal, break, continue, return, or throw, indicating the completion Type that occurs
  • [[Value]] Any ES language Value or null, representing the generated Value
  • [[Target]] Any string or empty string used to directly control the propagated label

The term abrupt completion denotes a completion of a non-normal type

Environment Record

Used to describe the resolution of names in nested functions or blocks

Abstract Closure

An Abstract Closure is used with a set of values to refer to an algorithmic step. Abstract closures are meta-values called in a functional style, such as closure(arg1, arg2), which executes the corresponding algorithmic step. In an algorithmic step to create an abstract closure, the value is captured by a list of aliases. When an abstract closure is created, it captures the values associated with each alias. When the closure is invoked, each captured value is referenced by the alias used to capture the value.

If an abstract closure returns a Completion Record, its [[type]] can only be normal or the throw abstract closure created as part of another syntax, such as

  1. Let the addend (addend) for 41
  2. Let the closure (closure) has a parameterx, which captures the addend and performs the following steps when called: Returnsx+addend
  3. letvalforclosure(1)
  4. Assertion: val is 42

Set

Used in the memory model to represent an unordered collection of elements whose elements are never repeated,

7. Abstract operations

Used inside the specification to help standardize semantic definitions, including type conversions, test and comparison operators, object operations, and iterating object operations.

8. Executable code and execution context

The chapter of the original specification is divided into two parts, in which the WeakRef part will be expanded in the memory management part. This chapter mainly talks about the rest, that is, the implementation details in the js execution process, related concepts are as follows

Environmental records

An Environment Record is a canonical type that combines an identifier and a specific variable with a function based on lexical nesting. Usually an environment record is associated with a syntactic structure (such as a function declaration or block statement), and each time the corresponding code is executed, a new environment record is created to record the corresponding identifier binding, which can then be used to fetch the corresponding variable. Each environment record has a [[OuterEnv]] field, which is another environment record or NULL, and is used to represent the logical nesting relationship between environment records. Environmental record types can be thought of as an object-oriented hierarchical relationships, an abstract class, three concrete classes (including the global environment record is located in the outermost layers of the scope, used for binding global object properties, and the statement on top of the script and a global environment are logically separate record, but is specified as an object on the record and declare the environment of the environment). There are other subclasses:

  • Environment Record (abstract)
    • Declarative Environment Record corresponds to syntax elements such as variable declarations, function declarations, or catch statements
      • function Environment Record
      • module Environment Record
    • Object Environment Record corresponds to syntax elements such as the with statement
    • global Environment Record

Execution context

The execution context is used by the implementation of ES to track runtime calculations. Each agent has at most one actual execution context at any time, which is called a running execution context. The execution context stack is used to keep track of the execution context. The executing context is always at the top of the stack. When control is passed to executable code that is not connected to the execution context, a new execution context is created. An execution context needs to specify state to track the execution progress of the relevant code, and each execution context contains the following state Components

  • Code Evaluation State contains any state used to execute, pause, or resume Code execution
  • Function This value is the Function object if the code executing the context is in a Function, otherwise null
  • Realm related Realm Records, which we’ll cover separately below.
  • ScriptOrModule related Module Record or Script Record, if it is in the context of the InitializeHostDefinedRealm create is null
  • Generator Generator Generator Object associated with the execution context
  • VariableEnvironment Some other environment records byvarDeclare some of the bindings created
  • LexicalEnvironment is used in this execution context to resolve the environment records referenced by the identifier, including usageletandconstAnd so on.

Create execution context

An execution context is a mechanism that is not directly accessed by code. We cannot create it directly, but as mentioned earlier, a new execution context is created when a piece of code is executed that is not yet associated with the execution context

function recursive(n = 0) { if (n > 1) throw new Error(); recursive(++n); } recursive(); console.log("Will never be logged..." );Copy the code

You start with a global context, and a recursive function creates a new execution contextUntil an error is thrown, you can see the various contexts nested in real time, the outermost being the global context



If I don’t make a mistake

function recursive(n = 0) { if (n > 1) return; recursive(++n); // * } recursive(); console.log("Will be logged!" );Copy the code

The context stack will look like this



Each execution context is pushed in and out of the stack in first-in order, with the context being executed at the top.

realms

Before computing, all code needs to be associated with a realm. Conceptually, a realm contains a set of built-in objects, a global environment, all code loaded by the global environment’s scope, and other associated states and resources. A realm is represented in the specification as a Realm Record, primarily for providing intrinsic values and accessing global objects. A Realm Record has the following fields

  • [[Intrinsics]] Intrinsic values for realm-dependent code
  • [[GlobalObject]] the GlobalObject of this realm
  • [[GlobalEnv]] The global environment record for this realm
  • [[TemplateMap]]
  • [[HostDefined]] Other values defined by the host

InitializeHostDefinedRealm

Realm is a state of the execution context component, while creating the first execution context needs to have a related realm, that need to be performed before all code execution InitializeHostDefinedRealm abstract method to initialize the realm. This includes the following steps

  1. throughCreateRealm()createrealm
  2. Let the new execution context be callednewContext
  3. Set up thenewContextThe Function is null
  4. Set up thenewContextIn the realm ofrealm
  5. Set up thenewContextScriptOrModule is null
  6. willnewContextPush the execution context stack, nownewContextIs the context in which it is being executed
  7. If the host requires an Exotic object to be used as a global object in a realm, letglobalIs a host-defined object, otherwise letglobalUndefined, which means that ordinary objects will be created as global objects.
  8. If the host needsthisBinding objects returned by realm’s global scope, instead of global objects, willthisValueIs a host-defined object, otherwisethisValueIs undefined, which means that realm’s this is bound to global objects
  9. performSetRealmGlobalObject(realm, global, thisValue).
  10. letglobalobjAs the SetDefaultGlobalBindings (realm)
  11. inglobalobjCreates properties of any global object
  12. returnNormalCompletion(empty)

agent

An agent consists of a series of execution contexts, an execution context stack, an executing context, an Agent Record, and an execution thread. Except for the thread of execution, everything else is unique to the agent.

An agent’s thread of execution executes a job independently of other agents in its execution context, unless the thread of execution is cross-agent, if the [[CanBlock]] property of the agent sharing the thread is true, such as some browsers that share the thread of execution across unrelated tabs. The code surrounding Agent is the agent when the executing thread of an agent executes jobs. This code has access to the executing context, context stack, and agent Record fields corresponding to the agent.

An agent is either the main program of a Web page or a Web worker

agent cluster

An agent cluster is a cluster of agents that can communicate with each other through a memory share such as SharedArrayBuffer. Each agent belongs to a cluster. For example, postMessage() used for communication in workers is based on SharedArrayBuffer.

job

What is a job? The definition of a job varies from version to version. A job is an abstract closure with no arguments that initializes a calculation when no other calculation is currently available in the program. Jobs are scheduled by the host environment. This specification describes the host hook HostQueuePromiseJob to schedule a job. The host can also define other abstract operations to schedule the job that take the abstract closure as a parameter and execute it at some future time. These implementations comply with the following requirements

  • At some point in the future, when there is no executing context and the execution context stack is empty, the implementation must:
    • Perform any host-defined preparation steps
    • Call the job
    • Perform any host-defined cleanup steps
  • There can only be one active job at any time
  • Once a job is executed, other jobs are allowed to start only after the job is completed
  • The abstract closure must return a Normal Completion to implement its own error handling.

The host does not need to uniformly treat scheduled jobs, and both Web browsers and Node.js give high priority to jobs that handle promises.

Here we get to the point where a job is really just some algorithmic step to be executed in the future, where promises have a higher priority and some additional restrictions. How to execute each job? We need to refer to the WHATWG HTML specification event-loop

event loop

The ES specification specifies the concerns of implementations such as V8, but ES is actually used by hosts such as browsers, so let’s take an HTML example. To coordinate events, UI, scripts, rendering, network requests, and so on, the user agent must use event Loop. Each event loop has one or more Task queues. Note that task queues are not queues, but sets, because the first step of an event loop is to select the first executable task, rather than queue the first task. The algorithm encapsulated by event Loop corresponds to such work

  • Events, which distributes events on a specific eventTarget object by a dedicated task (not all events are distributed this way)
  • Parsing, the HTML parser parses through tasks
  • Callback, which invokes the callback through a specialized task
  • Use resources, such as asynchronous FETCH resources
  • Responding to DOM operations

Each event loop has a microtask queue, which is a queue of microtasks that is initially empty. A microtask is a colloquial term for a task created through a microtask queue algorithm.

Each event loop has a Boolean value to perform the microtask check, starting with false to avoid repeated execution.

In other words, a macro task is a message queue organized by browsers to coordinate their work, and a micro task is a job. (In the ES specification, only one promise-related job was introduced, which was added to the HTML specificationqueueMicrotask), jobs form a job queue. In the browser, jobs have a higher priority and are executed before tasks in the task queue.Micro task is founded by task, when a task to complete the control to the user agent before the next loop, if there is a small task queue, in turn, performs all the tasks in the queue, pay attention to the task itself will generate micro tasks, until the task queue is empty, and then perform the necessary rendering, and then to the next task.

Here is a recommended site for visually executing JS, as shown below

HostEnqueuePromiseJob ( job, realm )

Is a host-defined abstract operation that schedules the execution of the abstract closure Job at some future time. The abstract closures used by the algorithm are used to process promises and others to operate at the same priority as promises.

If realm is null, no ES code will be executed and no ES objects will be created. The WHATWG HTML Specification uses realm checks as a way to run scripts.

Refer to the link

In addition to the corresponding links provided above, this section also references the following

  • The ECMAScript β€œExecutable Code and Execution Contexts” chapter explained
  • Using microtasks in JavaScript with queueMicrotask()
  • EventLoop
  • JavaScript job queue and microtasks
  • Macrotasks and Microtasks

9. Representations of ordinary and exotic objects

Built-in methods and built-in slots for ordinary objects

All normal objects have an internal slot called [[Prototype]], which is either null or an object that implements inheritance. Every common object has a Boolean internal slot [[Extensible]], which is used to implement Extensible related internal methods.

The function object

Function objects encapsulate parameterized code in a lexical environment and support dynamic evaluation of code. The function is also a normal function, except for the two slots mentioned above

  • [[Environment]] specifies the Environment in which the function resides, as outer Environment when calculating the code for the function
  • [[FormalParameters]] is the root Parse Node defined in the parameter list.
  • [[ECMAScriptCode]] is defined at the root parsing node of the function body
  • [[ConstructorKind]] uses base or derived to indicate whether or not a derived class is derived
  • [[Realm]] The Realm Record where the function resides
  • [[ScriptOrModule]] the Script Record or Module Record where the function is created
  • [[ThisMode]] defines the interpretive mode, this reference value for lexical | strict | global
  • [[Strict]] A Boolean value that indicates whether or not a function is in Strict mode
  • [[HomeObject]] If the function uses super, this value represents its __proto__ object
  • [[SourceText]] defines the SourceText of the function
  • [[IsClassConstructor]] Boolean representing whether or not a class constructor is used

Built-in function object

Even Exotic objects have [[Prototype]], [[Extensible]], and [[Realm]] built-in slots.

Built-in singular object

The specification defines a number of built-in singular objects, which behave like normal objects, but with some differences, as follows

  • The singular object of the binding function
  • Array singular object
  • String singular object
  • Arguments singular object
  • Integer-indexed singular object
  • Module namespace singular objects
  • Prototype immutable singular object

The Proxy object

A proxy object (distinguished from an agent) is a singular object with an internal slot [[ProxyHandler]] whose value is an object called a ProxyHandler object or null. See the Proxy section below for details

10. The source code

The source text

The ES code is represented in Unicode, and the ES source text is a series of code points. All code points from U+0000 to U+10FFFF are allowed

Type of source code

There are four types of source code

  • Global code, ES Script
  • The eval code
  • The function code
  • The module code

11. The lexical

This section covers js syntax, such as control characters or reserved words, for details please refer to MDN related content

The following part is not based on the specification, but mainly for referenceJavaScript reference

12. The expression

Expressions, operators, and keywords are covered here.

this

An execution context property that represents a reference to an object in non-strict mode and can be any value in strict mode.

Global context

The strict schema remains unchanged, pointing to a global variable globalThis

Function context

This depends on how the function is called. If this is not set in the context (called directly, such as fun()), the strict mode defaults to undefined and the non-strict mode defaults to globalThis, which is called a default binding. There are other binding methods

  • As a method on an object, this inside a function refers to that object, and this is called an implicit binding. Notice two things,
    1. Bind to the nearest object, such as O.A.B (), and b functions bind to object A
    2. If you assign a function as an object to another variable, it becomes the default binding, such asvar b=o.b; b()This is called binding loss
  • The call/apply binding is used to specify this and execute the function. In non-strict mode, non-object arguments to this are first converted to objects, where null and undefined are converted to globalThis and other raw values are converted to objects using the corresponding constructor
  • Bind, callf.bind(someObject)Will return a this pointersomeObjectAnd can only be called once by bind
  • The new call, in which this refers to the instance object returned, is invalid if another object is returned. Of the above binding methods, new calls have the highest priority, followed by the different call,apply, and bind bindings, followed by the implicit binding and finally the default binding
  • This in the arrow function has the same reference as this in the external context and cannot be bound by call,apply, or bind, where this is ignored.
  • As a DOM event handler, this points to the element that triggered the event
  • As an inline event handler, this points to the DOMT element where the listener resides

The class context

Classes are essentially functions, with some differences. All non-static methods in the class are added to this, and the constructor of the derived class does not have an initial this binding before super is called. In addition, functions in a class, like any normal function, depend on how they are called in the method, so it is necessary to bind them in the constructor.

class Car { constructor() { // Bind sayBye but not sayHi to show the difference this.sayBye = this.sayBye.bind(this); } sayHi() { console.log(`Hello from ${this.name}`); } get name() { return 'Ferrari'; }}Copy the code

new

You can instantiate a constructor or class using the new operator

new constructor[([arguments])]
Copy the code

The following operations are performed when the new keyword is executed

  1. Create an empty object, {}
  2. Sets the object’s [[prototype]] to the instantiated constructor or class
  3. Use this new object as the context for this
  4. If the called constructor does not return an object, this is returned
function CNew() { const [ctr, ...params] = Array.from(arguments); const obj = {}; //1 Object.setPrototypeOf(obj, ctr.prototype); //2 const result = ctr.apply(obj, params); //3 return typeof result === "object" ? result : obj; / / 4}Copy the code

Increasing and decreasing

  • A++/A– return plus 1/ minus 1
  • ++A/–A adds 1/ subtracts 1 and returns

Unary operator

  • Delete Removes a property on an object that will be released if there are no other references to the property
  • Void Discards the return value of an expression and returns undefinedjavascript:Agreements, for example
<a href="javascript:void(document.body.style.backgroundColor='green');" > Click here for green background </a>Copy the code
  • Typeof returns a string representing the typeof the argument, with optional parentheses, where null of the original type returns object and other types return the corresponding type. Object function objects return function, others return object.
  • The + unary plus sign is used to convert the operand to the number represented, and nothing else
  • Minus unary, convert to number, and then take the negative

Logical operator

  • ! Logic is not
  • && logic and,expr1 && expr2, expr1 can turn into true is returned expr2, otherwise returns expr1, than the back of the | | operation first
  • | | logic orexpr1 || expr2If expr1 can be converted to true, expr1 is returned, otherwise expr2 is returned
  • ?? Nullish Coalescing operator. If the left operand is null or undefined, the right operand is returned. Otherwise, the left operand is returned

Mathematical operations

Returns the number of computed results

  • +
  • /
  • *
  • % more than take
  • ** Index operation

Relations between operating

Returns a Boolean value indicating whether a specific relationship exists

  • In Specifies whether an object has a specified attribute, both inherent and inherited
  • Instanceof indicates whether the prototype property of the former is present in the prototype chain of the latter
  • < <, the basic steps for comparison are as follows
    • Called if it is an objectSymbol.ToPrimitive, whose hint parameter is ‘number’, which is converted to number
    • If both are strings, they are compared by string based on their Respective Unicode code points
    • Otherwise, a non-numeric value is converted to a numeric type
    • Return false if NaN exists
    • Otherwise compare the number size
  • > Greater than, refer to less than
  • < =
  • > =

O etc.

Returns a Boolean value indicating equality

  • == If the two operands are of different types, an attempt will be made to convert them and then compare them
    • If both operands are objects, they point to a reference
    • If one is null and the other is undefined, it is equal
    • If the types are different, convert before comparing
      • Comparing numbers and strings converts strings to numbers
      • If a Boolean value exists, it is converted to a number
      • If one is an object and one is a string or number, it is converted to the original type using valueOf() and toString() of the object
    • If two operands are of the same type
      • String. The same characters are equal
      • Numbers, Β±0 is equal, NaN is not equal to other numbers
      • Boolean value
  • ! = is the opposite of ==
  • === is strictly equal, different types are considered different, other types are the same as ==
  • ! == is the opposite of strict equality

An operator

Before the bit-based operation, the value must be converted to a 32-bit binary integer. If the value exceeds 32 bits, the value will be discarded and then converted to a standard JS value. Note that binary is represented by complement code, and the calculation method is

  • After the original code is directly converted to binary, 0 is added before it, and the highest bit is the sign bit. The positive number is 0, and the negative number is 1. If it is converted to 8-bit binary, the original code of 11 is 00001011, and the original code of -11 is 10001011.
  • Inverse code, negative number divided by sign bit all bits are negative, positive number unchanged
  • Complement, negative inverse +1, positive number unchanged

Bitwise operators include two types, one is the logical operator and the other is the move operator

Logical operator

  • The result is ~x=-(x + 1).
 9 (base 10) = 00000000000000000000000000001001 (base 2)
               --------------------------------
~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
Copy the code
  • & bitwise and, performing and operating on each pair of bits, is 1 if both are 1
     9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
Copy the code
  • | bitwise or, for each pair of bits implementation or operation, when both of zero is zero, such as x | 0 means integer x
     9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
Copy the code
  • ^ Bitwise or, each pair is not equal to 1
     9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
Copy the code

Move operator

The two operators represent the operand and the length moved, respectively

  • Any bits that the << left-shift operator moves more than left are discarded and replaced with 0 on the right, x<
   9 (base 10): 00000000000000000000000000001001 (base 2)
                  --------------------------------
9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
Copy the code
  • The >> right-shift operator is discarded and the leftmost bits are copied. Since the symbol bits do not change, it is called symbol propagation
.    9 (base 10): 00000000000000000000000000001001 (base 2)
                  --------------------------------
9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
Copy the code
  -9 (base 10): 11111111111111111111111111110111 (base 2)
                   --------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
Copy the code
  • >>> No sign moves right and right over will be discarded, the left side of the 0, so the sign bit will become 0, positive numbers are the same as normal right shift
  9 (base 10): 00000000000000000000000000001001 (base 2)
                   --------------------------------
9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
Copy the code
     -9 (base 10): 11111111111111111111111111110111 (base 2)
                    --------------------------------
-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
Copy the code

Conditional operator

  • (condition ? ifTrue : ifFalse)

Optional Chaining operator

  • ? If the reference is null or undefined, undefined is returned instead of an error
obj.val? .prop obj.val? .[expr] obj.arr? .[index] obj.func? .(args)Copy the code

The assignment operator

  • =
  • * =
  • * * =
  • / =
  • % =
  • + =
  • – =
  • < < =
  • > > =
  • > > > =
  • & =
  • ^ =
  • | =
  • && =
  • | | =
  • ?? =
  • [a, b] = [1, 2] {a, b} = {a:1, b:2} Destruct assignment
let a, b, rest; [a, b] = [10, 20]; console.log(a); // 10 console.log(b); // 20 [a, b, ...rest] = [10, 20, 30, 40, 50]; console.log(a); // 10 console.log(b); // 20 console.log(rest); // [30, 40, 50] ({ a, b } = { a: 10, b: 20 }); console.log(a); // 10 console.log(b); // 20 // Stage 4(finished) proposal ({a, b, ... rest} = {a: 10, b: 20, c: 30, d: 40}); console.log(a); // 10 console.log(b); // 20 console.log(rest); // {c: 30, d: 40}Copy the code

You can use the default values

var {a = 10, b = 5} = {a: 3}; console.log(a); // 3 console.log(b); / / 5Copy the code

New variable name

var {a:aa = 10, b:bb = 5} = {a: 3}; console.log(aa); // 3 console.log(bb); / / 5Copy the code

Comma operator

  • Joins multiple expressions to evaluate separately and returns the last one

13. Statements and declarations

A.js program contains multiple statements with correct syntax. A statement may span multiple lines, and multiple statements may be separated by semicolons on one line.

The control flow

  • Block A block statement that contains zero or more statements, used by{}Contains. And usuallyif... elseIn combination with let,const, or strict mode, individual blocks have block scope, otherwise they remain global.

The label can be used for identification or as a break to drop the corresponding block

LabelIdentifier: {
  StatementList
}
Copy the code
  • Break terminates the current loop, switch, or label declaration, and then transfers control of the program to another statement
break [label];
Copy the code

When label is used, it must be nested in the corresponding label. Label can refer to a common block statement.

outer_block:{
  inner_block:{
    console.log ('1');
    break outer_block;      // breaks out of both inner_block and outer_block
    console.log (':-(');    // skipped
  }

  console.log ('2');        // skipped
}
Copy the code
  • Continue Stops the current loop or the current iteration tagged loop and continues with the next iteration
continue [label];
Copy the code

Such as

let text = '';

for (let i = 0; i < 10; i++) {
  if (i === 3) {
    continue;
  }
  text = text + i;
}

console.log(text);
// expected output: "012456789"
Copy the code
  • An Empty statement is one with no statement and only a semicolon
let arr = [1, 2, 3]; // Assign all array values to 0 for (let i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ; console.log(arr); / / [0, 0, 0]Copy the code
  • if… else
  • switch
  • throw
  • try… catch
try {
  try_statements
}
[catch [(exception_var)] {
  catch_statements
}]
[finally {
  finally_statements
}]
Copy the code

The statement

Variable naming

Variable names have two limitations

  • Contains only letters, digits, $and _
  • The first character cannot be a number

Variable creation process

There are three steps: create, initialize, and assign

var a=1 
Copy the code

In this example, creating means creating the variable A, but not saving any value, so it cannot be used; Initialization means that a variable is initialized to undefined before it is assigned; Assignment is manually assigning a value of 1 to a variable.

The declarative approach

You can declare variables using var,let, and const, but they differ in the following ways

  • The old declaration, creation and initialization of var is deprecated
  • Let is similar to VAR, but with the following differences
    • Only valid within a code block
    • Creation is promoted, so nothing can be done before let
    • Duplicate declarations are not allowed
  • Const is similar to let, except that it must be initialized after being declared and cannot be changed

Creating a function is divided into function expressions, which use the function keyword, and function declarations, which declare a variable and hold the function. When declaring a function using the function function, all three steps of variable creation are enhanced

The iteration

  • do… While executes a statement until the condition is false, at least once
do
   statement
while (condition);
Copy the code
  • For contains three optional comma-separated expressions followed by a statement
for ([initialization]; [condition]; [final-expression])
   statement
Copy the code

If let is used, the declared variable is the local variable of the following statement

  • for… In iterates over the enumerable properties of an object, including inherited, but not including symbol properties
for (variable in object)
  statement
Copy the code
var obj = {a: 1, b: 2, c: 3};

for (const prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
Copy the code
  • for… Of iterable objects (including Arrays, array-like objects, iterators and generators)
for (variable of iterable) {
  statement
}
Copy the code
const iterable = [10, 20, 30];

for (const value of iterable) {
  console.log(value);
}
// 10
// 20
// 30
Copy the code
  • for await… Of iterates over an asynchronous iterated object, which can only be used in async function
var asyncIterable = { [Symbol.asyncIterator]() { return { i: 0, next() { if (this.i < 3) { return Promise.resolve({ value: this.i++, done: false }); } return Promise.resolve({ done: true }); }}; }}; (async function() { for await (num of asyncIterable) { console.log(num); }}) (); // 1/2Copy the code
  • while
while (condition)
  statement
Copy the code

other

  • debugger
  • export
  • Label gives the statement an identifier, which is used for break and continue
  • With extends the scope for statements, has performance and semantic problems, and is prohibited in strict mode

14. The Function and the class

function

A function, so to speak, is a subroutine that can be called either by external code or recursively from within. Like a program itself, a function is made up of a series of statements, called the function body. In JS, functions are first-class objects because they can have properties and methods like any other object and can be called

Define a function

  • Function declarations, or function statements, are promoted
function name([param[, param[, ... param]]]) {
   statements
}
Copy the code
  • Function expressions, whose syntax is much like function declarations, can be used to define anonymous or named functions and will not be promoted.
function [name]([param[, param[, ... param]]]) {
   statements
}
Copy the code
var myFunction = function() {
    statements
}
Copy the code

If the Function is used only once, you can use IIFE (Immediately Invoked Function Expression)

(function() {
    statements
})();
Copy the code
  • Generator function declaration (or function* statement)
function* name([param[, param[, ... param]]]) {
   statements
}
Copy the code
  • Generator function* expression
function* [name]([param[, param[, ... param]]]) {
   statements
}
Copy the code
  • Arrow function expression
([param[, param]]) => {
   statements
}

param => expression
Copy the code
  • The Function constructor, which is not recommended because the Function body is a string, prevents JS engine optimization
new Function (arg1, arg2, ... argN, functionBody)
Copy the code
  • GeneratorFunction constructor
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
Copy the code

The arguments object

Is an array object that can be accessed in the function body and contains parameters passed to the function, including the following properties

  • Arguments. callee specifies the function to which the arguments belong. Use is prohibited in strict mode
  • Arguments. length Specifies the length of the input parameter
  • Arguments [@@iterator] returns an iterator

Function default arguments allow the default parameter to be used when passed in with no value or undefined.

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
    statements
}
Copy the code

The default parameters can be used later

function greet(name, greeting, message = greeting + ' ' + name) { return [name, greeting, message]; } greet('David', 'Hi'); // ["David", "Hi", "Hi David"] greet('David', 'Hi', 'Happy Birthday! '); // ["David", "Hi", "Happy Birthday!"]Copy the code

Structure parameters with default values

function f([x, y] = [1, 2], {z: z} = {z: 3}) { return x + y + z; } f(); / / 6Copy the code

Rest parameter syntax allows us to represent an indefinite number of parameters as an array

function(a, b, ... theArgs) { // ... }Copy the code

Method on an object

Var obj = {property(parameters...); {}, * the generator (parameters)... {}, async Property (parameters...) {}, async* generator(parameters...) {}, // with computed keys: [property](parameters...) {}, * / generator (the parameters...). {}, async [property](parameters...) {}, // compare getter/setter syntax: get property() {}, set property(value) {} };Copy the code

The set syntax is called when the corresponding property is set, and get is called when the corresponding property is obtained.

Arrow function

Is a variant of the traditional function expression, but it has some limitations

  • Constructors cannot be used
  • Can’t bind to this,super
  • You cannot use the arguments or new.target keyword
  • The Apply,call, or bind methods do not apply
  • You can’t use yield

class

Class is a template for creating objects. Class in JS is based on prototypes, but there are other uses as well.

Define a class

Like functions, there are two ways to define them, class expressions or class declarations.

The class declaration

Will not raise

class Rectangle { constructor(height, width) { this.height = height; this.width = width; }}Copy the code
The class expressions
// unnamed let Rectangle = class { constructor(height, width) { this.height = height; this.width = width; }}; console.log(Rectangle.name); // output: "Rectangle" // named let Rectangle = class Rectangle2 { constructor(height, width) { this.height = height; this.width = width; }}; console.log(Rectangle.name); // output: "Rectangle2"Copy the code

Class body and method definition

  • The body of the class is executed in strict mode
  • Constructor, a special method for creating and initializing objects created by a class. A class can have only one object. You can use super to call the superclass constructor.
  • Prototype methods refer to the methods of objects in the function section
class Rectangle { // constructor constructor(height, width) { this.height = height; this.width = width; } // Getter get area() { return this.calcArea() } // Method calcArea() { return this.height * this.width; } } const square = new Rectangle(10, 10); console.log(square.area); / / 100Copy the code
  • Static method, use static method
  • Field declarations, both public and private, the latter preceded by a pound sign (#)
class Rectangle { #height = 0; width; constructor(height, width) { this.#height = height; this.width = width; }}Copy the code

A subclass

Using extends

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name); // call the super class constructor and pass in the name parameter
  }

  speak() {
    console.log(`${this.name} barks.`);
  }
}

let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.
Copy the code

You can also extend the constructors declared by regular methods.

Species

Use custom built-in constructors, such as

class MyArray extends Array { // Overwrite species to the parent Array constructor static get [Symbol.species]() { return Array; }} let a = new MyArray(1,2,3); let mapped = a.map(x => x * x); console.log(mapped instanceof MyArray); // false console.log(mapped instanceof Array); // trueCopy the code

Mix-ins

Is a template for class. A class can only have one parent, so a mix-in needs to provide a parent

let calculatorMixin = Base => class extends Base {
  calc() { }
};

let randomizerMixin = Base => class extends Base {
  randomize() { }
};
Copy the code
class Foo { }
class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
Copy the code

15. Scripts and Modules

Script is a concept relative to module, with the following major differences.

Scripts Modules
HTML element <script> <script type=”module”>
Default mode non-strict strict
Top-level variables are global local to module
Value of this at top level window undefined
Declarative imports (import statement) no yes
Programmatic imports (Promise-based API) yes yes
File extension .js .js

Modules and ES Modules: A Cartoon deep-dive

background

The process of writing code is the process of managing variables, and maintaining those variables becomes a problem when the project becomes large. In JS there is the concept of scope to help us maintain code. The top-level variables we used in previous scripts were basically in global scope, and there are some problems with this usage

  • Different script introductions need to be ordered
  • The dependencies of different files are not easy to distinguish
  • Globally-scoped variables are difficult to maintain

In addition, different variables can be defined using the function scope, but variables declared in the function scope are difficult to access from outside.

So we can introduce modules, we can break up the code into many pieces and put them into a single module, have each module maintain its own scoped variables, then share specific variables by explicitly exporting and importing, and the dependencies become clear.

The working process

Using a module goes through three steps

  • The Construction phase needs to start with the entry file
    • Perform module resolution to find dependent modules
    • Load module
    • Parsing all modules into individual data structures, Module Records
  • Instantiation: a Module instance consisting of code and data. The Instantiation process combines Module Records and maps exported imported variables to addresses in memory. Note that this is different from the CommonJS implementation, which is an imported copy, meaning that the imported module is not aware of any subsequent changes to the corresponding variable. In ES Module, exported variables can be modified at any time. Imported files cannot modify these values, but they can modify the attributes of imported objects.
  • Executing the top-level code populates the memory address of the corresponding variable only once per module.



Because of the Live Bindings for variables in ES Module, circular references can be handled very well, such as

In this example, commonjs is used, starting from main.js, and executing until the require statement loads the counter module, which attempts the message variable, which is undefined, and returns to main after the counter file is finished executing, Later, even if message has a value, the variable introduced in count will still be undefined, but if it’s ES Module, the counter module will eventually get the correct value.

use

Js native module use and we usually use a variety of third-party tools to achieve very similar, here is a rough look

export

A module is an independent file. All variables inside the file are not available externally. If you want external files to be able to read variables from this module, you need to export variables within the module using the export keyword. Such as:

// profile.js
export var a = 1;
export var b = 2;
export var c = 3;
Copy the code

The following is equivalent, which is clearer (at the bottom you can see which variables are derived) :

var a = 1;
var b = 2;
var c = 3;
export {a, b, c}
Copy the code

The export command can export functions or classes as well as variables. The export function

export function foo(){}
function foo(){}
function bar(){}
export {foo, bar as bar2}
Copy the code

Where as above means to rename the exported variable. Note that variables exported by export can only be at the top level of the file. If they are in block-level scope, an error will be reported. Such as:

function foo() {
  export 'bar'; // SyntaxError
}
Copy the code

Derived classes

Export default class {} //Copy the code

The output value of the export statement is dynamically bound to the module to which it belongs.

// foo.js
export var foo = 'foo';

setTimeout(function() {
  foo = 'foo2';
}, 500);

// main.js
import * as m from './foo';

console.log(m.foo); // foo
setTimeout(() => console.log(m.foo), 500); // foo2
Copy the code

import

The import command can import parts exported by other modules through export.

// abc.js
var a = 1;
var b = 2;
var c = 3;
export {a, b, c}
Copy the code
//main.js
import {a, b, c} from './abc';
console.log(a, b, c);
Copy the code

If you want to rename the imported variable, use the AS keyword (which can also be used in the export).

import {a as aa, b, c};
console.log(aa, b, c)
Copy the code

If you want to input and then output a module in a module, the import statement can be written together with the export statement.

import {a, b, c} form './abc'; Export {a, b, c} from './ ABC '; export {a, b, c} from '.Copy the code

The whole loading of modules uses the * keyword.

// abc.js
export var a = 1;
export var b = 2;
export var c = 3;
Copy the code
// main.js
import * from as abc form './abc';
console.log(abc.a, abc.b, abc.c);
Copy the code

export default

Curly braces {} are required when exporting multiple variables at the same time, and curly braces are required when importing. The output of export defalut does not require curly braces. The output of import export default does not require curly braces.

// abc.js var a = 1, b = 2, c = 3; export {a, b}; export default c; import {a, b} from './abc'; import c from './abc'; Log (a, b, c) // 1, 2, 3Copy the code

Essentially, export default outputs a variable or method called default, which is entered without curly braces.

// abc.js export {a as default}; // main.js import a from './abc'; Import {default as aa} from './ ABC '; console.log(aa);Copy the code

Dynamic import

Return a Promise

import('/modules/my-module.js')
  .then((module) => {
    // Do something with the module.
  });
Copy the code

Error handling and language extension

There are some considerations in language implementation that are not expanded here.

17. Standard built-in objects

There are built-in objects available every time a Script or Module is executed: a global object (globalThis), a built-in global object (globalThis), and other built-in global objects that can be accessed via the initial properties of the global object or indirectly as properties of the built-in object.

18. Global objects

Global objects conform to the following characteristics

  • Is created before entering any execution context
  • There is no [[call]] built-in method and cannot be called as a function
  • There is a [[Prototype]] built-in hook that is host-defined
  • There may be some host-defined properties outside of the specification, and there may also be a property that is the global object itself.

Only global object value and function properties are covered here; constructor and other properties are covered in a later section.

The value property of the global object

  • GlobalThis is the globalThis value. Previously, accessing this in different host environments required different syntax, such as Window or global.
  • POSITIVE_INFINITY Infinity
  • NaN is Number.NaN, not a Number
  • Undefined means undefined, a variable is undefined if it is not assigned a value, and a method or statement returns undefined by default

Function properties of a global object

  • Eval executes string code. It is unsafe and performs poorly. Do not use eval
  • isFinite()
  • isNaN()
  • ParseFloat () converts string arguments to floating-point numbers, if not strings first.
  • parseInt(string, radix)
  • URI codec
    • encodeURI()/decodeURI()
    • encodeURIComponent()/decodeURIComponent()

The results are as follows

var set1 = "; , /? : @ & = + $"; Var set2 = "-_.! ~ * '() "; Var set3 = "#"; Var set4 = "ABC ABC 123"; // Alphanumeric characters and Spaces console.log(encodeURI(set1)); / /; , /? :@&=+$ console.log(encodeURI(set2)); / / - _.! ~*'() console.log(encodeURI(set3)); // # console.log(encodeURI(set4)); // ABC%20abc%20123 (the space gets encoded as %20) console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24 console.log(encodeURIComponent(set2)); / / - _.! ~*'() console.log(encodeURIComponent(set3)); // %23 console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20)Copy the code

Because the former cannot encode symbols (such as “&”, “+”, and “=”) to produce a URL suitable for HTTP requests, use the latter.

19. Basic objects

Is the basis for other objects

Object

Almost all objects (except those created using Object.create(null) or modified by Object.setProtoTypeof) are instances of Object. A particular Object inherits properties from Object.prototype, some of which may be overridden. Objects can be created using constructors or literals. The delete operator can be used instead of a specific way to delete properties from an object

The constructor

new Object()
new Object(value)
Copy the code

Returns an empty object if the argument is undefined or null, otherwise returns the corresponding object type. If the object itself is returned directly.

A static method

The stereotype

  • Object.create(proto, [propertiesObject]) takes an existing Object as the prototype of the newly created ObjectObject.defineProperties()Is used to specify the property descriptor.
  • Object.getprototypeof () returns the [[Prototype]] property
  • Object.setprototypeof (obj, prototype) Sets the [[prototype]] property

Attributes related to

  • Object.assign(target, … Sources) copies enumerable own properties from one or more source objects to the target object, returning the target object
  • Object.defineproperty (obj, prop, Descriptor) Defines a new property or modifies an existing property on an Object, and then returns the Object
  • Object.defineproperties (obj, props) Defines or overrides an Object on an Object, and returns the Object
  • Object. GetOwnPropertyDescriptor (obj, prop) returns the property descriptor Object
  • Object. GetOwnPropertyDescriptors (obj) return all attributes of the Object descriptor

Iterative related

  • Object.entries(obj) returns the given Object’s own enumerable array of key-value pairs ([key, value][])
  • Object.fromEntries() Object.entriesThe inverse operation of
  • Object. GetOwnPropertyNames (obj) return to its own enumeration and an array of enumeration attributes, does not contain the symbol properties
  • Object. GetOwnPropertySymbols (obj) return to its own symbol attribute array
  • Keys (obj) returns an array of its own enumerable properties
  • Object.values(obj) returns an array of its own enumerable property values

Attribute freezing correlation

  • Freeze (obj) No property of an Object can be modified. If the property of an Object is an Object, the property can be modified unless it is also a frozen Object. Return the frozen Object, affecting the prototype chain
  • Object. PreventExtensions (obj) to make it unextensible, i.e. not add properties and not affect the prototype chain
  • Compared to object.seal (obj) and Object.freeze(), existing properties can be modified
  • Object.isExtensible(obj)
  • Object.isFrozen(obj)
  • Object.isSealed(obj)

Freeze >seal>Extension

Sentence etc.

  • Object. Is (value1, value2) determines whether two values are equal. The difference between === is that the former distinguishes Β±0 and considers NaN to be equal to itself

Instance attributes

  • The constructor in addition toObject.create(null)All objects other than those generated have this property pointing to the corresponding constructor. This property can be modified. If theObject.createObject whose property is the constructor of the parameter, for example
function Parent() {} Parent.prototype.parentMethod = function parentMethod() {}; function Child() {} Child.prototype = Object.create(Parent.prototype); // re-define child prototype to Parent prototype Child.prototype.constructor = Child; / / default is the Parent. The prototype. The constructor, that is, the function the Parent () {}Copy the code
  • __proto__ is for reference only, do not use it

Instance methods

  • Obj.hasownproperty (prop) checks whether the property is self, including the symbol property
  • PrototypeObj. IsPrototypeOf (object) check whether prototypeObj on the object prototype chain, different from "object instanceof AFunction"Indicates whether AFunction. Prototype is on the Object prototype chain.
  • Obj. PropertyIsEnumerable (prop) returns if the property is itself enumerable
  • Object.valueof () returns the original valueOf the object. None of the original types return itself. Date returns the number of milliseconds
  • Obj.tostring () returns a string representation of the object, which is the default[object type]Where Type is the type of the object
  • Obj.tolocalestring () returns the result of calling toString(), but is overridden by many objects

Function

Each Function is a Function object

Instance attributes

  • Name Specifies the name of the function
  • Length Specifies the number of parameters

Instance methods

  • Func.apply (thisArg, [argsArray]) calls the function with a given this, with arguments supplied as an array
  • Call ([thisArg[, arg1, arg2…argN]]) differs from apply in that it is a list of arguments, not an array
  • Bind (thisArg[, arg1[, arg2[,…argN]]]) creates a new function, this is the specified argument, and the other arguments are prefabricated as the new function
  • Function.tostring () returns the source of the function

Boolean

Is an object wrapper for a Boolean value. ToString returns a quoted Boolean value

Symbol

Symbol is a primitive type created by calling symbol ([description]). Each return value is unique. The parameter is a string that describes the symbol, and the return value is unique even if the parameters are the same.

A global symbol

Use the Symbol. For(key) method and Symbol. KeyFor (sym) method to register symbols globally. The latter returns the specified key based on the specified symbol, or undefined if not found.

Find the symbol property

Object.getOwnPropertySymbols()

Well known symbol

Symbol has static properties that let you get methods in built-in objects that are called when the built-in objects execute specific methods. The following is the iteration of the operation corresponding to the static attribute

  • Symbol.iterator for… of
  • Symbol.asyncIterator for await of

Regular expression

  • Symbol.match String.prototype.match()
  • Symbol.replace String.prototype.replace()
  • Symbol.search String.prototype.search()
  • Symbol.split String.prototype.split()

other

  • Symbol.hasInstance instanceof
  • Symbol.isConcatSpreadable Array.prototype.concat()
  • The value of an object that owns and inherits the attribute name is excluded from the related object bound to the environment.
  • Symbol.species A constructor function used to create derived objects.
  • Symbol. ToPrimitive A method to convert an object to a primitive data type.
  • Symbol.toStringTag Object.prototype.toString()

reference

  • Symbols in ECMAScript 6

Error

Object thrown when a runtime error occurs, which is the base class, among many other error types in JS

Numbers and dates

Number

The representation of the 64-bit floating-point format of the numeric type and the scope of the representation, precision calculation methods, etc., have been described previously, and will not be described here.

Numeric literal

  • The most common base of the decimal system, which can be preceded by 0, is considered octal if all numbers are less than 8
  • Exponential is expressed in the format ofbeN, where B refers to the base number, e to the exponent symbol, and N to the exponent
  • Binary starts with either 0b or 0b
  • Octal starts with an 0o or 0O
  • The hexadecimal number starts with 0x or 0x

Static attributes

  • Number.EPSILON represents the difference between the smallest floating point Number greater than 1 and 1
  • Safe integers, in this range can accurately represent integers, such asNumber.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2To true
    • The largest Number. MAX_SAFE_INTEGER
    • Number. MIN_SAFE_INTEGER minimum
  • Denotes scope,
    • Number.MAX_VALUE Specifies the maximum positive Number
    • Number.MIN_VALUE Specifies the minimum positive Number
    • Number.POSITIVE_INFINITY
    • Number.NEGATIVE_INFINITY
  • Number.NaN

A static method

  • Number.isNaN()
  • Number.isFinite()
  • Number.isInteger()
  • Number.isSafeInteger()
  • Number.parseFloat(string)
  • Number.parseInt(string, [radix])

Instance methods

  • NumObj. ToExponential ([fractionDigits]) is expressed as an exponential representation with parameters that specify the number of decimal places. Between 0 and 20, the default is to reserve as many digits as possible based on the number
  • Numobj.tofixed ([digits]) uses a non-exponential fixed-point representation, with the argument reserved several digits after the decimal point. The default is 0
  • Numobj.toprecision ([precision]) returns a fixed-point or exponential string, with the argument representing precision, that is, several non-zero digits
  • NumObj. ToString ([radix]) base conversion, parameters are numbers between 2 and 36, return the corresponding base string
  • Numobj.tolocalestring ([locales [, options]]) returns a string representation of the number specific locale, where the arguments are used to define the behavior of the function. See intl.numberFormat () constructor

BigInt

Is a built-in object used to represent integers other than safe values, followed by n when expressed in literals

Math

BigInt is a built-in object that has properties and methods that represent mathematical constants and computations. It cannot be used with bigInt

Static attributes

  • Math. PI PI

Logarithmic correlation

  • Math.e The base of the natural logarithm, ln
  • Math.log of 2 the natural log of 2
  • Math.log 10 The natural log of 10
  • Math.LOG2E Log base 2 of e
  • Math.LOG10E log base 10 of e

The square root

  • Math.sqrt 1_2 Β½ square root
  • Math.SQRT2 the square root of 2

A static method

  • Math. Abs (x) the absolute value
  • Math.max([x[, y[,…]]]) Maximum value of multiple values
  • Math.min([x[, y[,…]]]) The minimum value of multiple values
  • Math.pow(x, y) x to the y
  • Math.random() yields a pseudorandom number between 0 and 1 (front closed and back open), which does not provide a secure random number
  • Math.sqrt(x) the square root of a number
  • Math.cbrt(x) returns the cube of some number as x
  • Math.clz32(x) The number of leading zeros in a 32-bit integer
  • Math.exp(x) e to x squared
  • Math.fround(x) is the closest single precision floating point number
  • Math.imul(x, y) 32 – bit integer multiplication
  • Math.log(x) of a number equal to ln
  • Math. Log1p (x) The natural logarithm of the sum of a number plus 1
  • Math.log10(x) A logarithm of base 10
  • Math.log2(x) A logarithm of base 2

The approximate

  • Math.ceil(x) rounded up
  • Math.floor(x) is rounded down
  • Math.round(x) The rounded integer
  • Math.trunc(x) returns the integer part

Date

Represents the number of milliseconds from Midnight on January 1, 1970, UTC to the present

The constructor

new Date()
new Date(value)
new Date(dateString)
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
Copy the code

A static method

  • Date.now() returns the number of milliseconds represented
  • Date.parse(dateString) Returns the number of milliseconds to parse a string representing a Date
  • Date.utc () takes the same arguments as the constructor and returns the number of milliseconds

Instance methods

years

  • GetFullYear () 4-digit year
  • setFullYear()

month

  • GetMonth () Specifies the month from 0 to 11
  • setMonth()

day

  • GetDate () from 1 to 31
  • setDate()

What day

  • GetDay () 0 to 6 has no method for setting the day of the week

when

  • GetHours () 0 to 23
  • setHours()

points

  • GetMinutes () 0 to 59
  • setMinutes()

seconds

  • GetSeconds () 0 to 59
  • setSeconds()

ms

  • The getMilliseconds () 0 to 999
  • setMilliseconds()

other

  • GetTime () time stamp
  • GetTimezoneOffset () Specifies the time difference between utc and the current time zone, in mins, for example, -480
  • ToDateString () corresponds to the format, for example, Wed Jul 28 1993
  • ToISOString () The format yyyY-MM-DDTHh: MM: sS.ssSz
  • ToJSON () is similar to toISOString()
  • ToLocaleDateString ([locales [, options]]) Local format output, parameter reference
  • toLocaleString([locales[, options]])

21. Text processing

String

Used to represent and manipulate character sequences

Creating a string

It is divided into literal and constructor methods, the last of which specifies that template literals can be interpolated. Constructor methods are described later

const string1 = "A string primitive";
const string2 = 'Also a string primitive';
const string3 = `Yet another string primitive`;
Copy the code

Template literals

The use of backquotes instead of quotes is a string literal that allows the embedding of expressions (${expression}) with multi-line and interpolation capabilities, formerly known as module strings.

Another way to use Tagged templates is to parse a template string using a function where the first parameter is an array of string values and the rest are interpolations in the template string, for example

var person = 'Mike';
var age = 28;

function myTag(strings, personExp, ageExp) {

  var str0 = strings[0]; // "that "
  var str1 = strings[1]; // " is a "

  // There is technically a string after
  // the final expression (in our example),
  // but it is empty (""), so disregard.
  // var str2 = strings[2];

  var ageStr;
  if (ageExp > 99){
    ageStr = 'centenarian';
  } else {
    ageStr = 'youngster';
  }

  return str0 + personExp + str1 + ageStr;

}

var output = myTag`that ${ person } is a ${ age }`;

console.log(output);
// that Mike is a youngster
Copy the code

In addition, the first argument to the tag function has an attribute row, which gives us access to the raw string of the template string

function tag(strings) {
  console.log(strings.raw[0]);
}

tag`string text line 1 \n string text line 2`;
// logs "string text line 1 \n string text line 2" ,
// including the two characters '\' and 'n'
Copy the code

Character access

There are two ways to access characters in a string. The first is charAt()

'cat'.charAt(1) 
Copy the code

The other is to access it as an array

'cat'[1]
Copy the code

Comparison string

Can use number greater than or less than more directly, you can also use referenceStr. LocaleCompare (compareString [, locales [options]]), the parameter and the language environment, if the previous character than the parameter character before it returns a negative number

Escape character

See Escape Notation, for example

  • \ n a newline character
  • \ t tabs
  • Backspace \ b
  • Enter \ r
  • \’ quote character
  • \xXX represents a character in two hexadecimal ascII codes
  • \uXXXX represents one character unicode in four hexadecimal numbers
  • \ u {X… 1 to 6 UTF-32 Unicode characters

A static method

  • String.fromcharcode (num1[,…[, numN]]) converts a series of UTF-16 code points to strings ranging from 0 to 65535 (0xFFFF).
  • String.fromcodepoint (num1[,…[, numN]]) new method for converting codepoints to strings, supports codepoints larger than 65535, Previous methods use two UTF-16s (called surrogate pairs) to represent characters beyond this range, for exampleString.fromCharCode(0xD83C, 0xDF03);The new method only requiresString.fromCodePoint(0x1F303)

Instance attributes

Contains no re correlation, which is covered in the re section

  • Get utF-16 STR [pos] and str.charat (pos) at a position, the difference being that the former returns undefined and the latter returns an empty string if no character is found.
  • Gets the Unicode numeral charCodeAt(index) and codePointAt(pos) corresponding to the specified position, where the latter recognizes four-byte characters
  • ToLowerCase () and toUpperCase() change case
  • Find the substring positions str.indexof (substr, pos) and str.lastIndexof (substr, pos). The former searches from front to back, the latter from back to front, and the second argument is the starting position of the search
  • Contains str.includes(substr, pos), str.startswith (substr, pos), str.endswith (substr, length). The second parameter further limits the scope of the search
  • Get substrings
    • Str.slice (start [, end]) returns the portion of the string from start to (but not including) end, counting from the end if the position is negative
    • Str.substring (start [, end]) and slice should be treated as 0 if they are negative and end with a large number
    • Str.substr (start [, length]) gets a string of length from start, which can be negative
  • Str.concat (str2 [,…strN]) concatenates multiple string text, returning a new string
  • fill
    • Str.padend (targetLength [, padString]) fills the end of the target string to the targetLength and returns the filled string, with Spaces by default
    • Str.padstart (targetLength [, padString]) fills the header
  • Repeat str.repeat(count) The string repeats count times
  • Split str.split([separator[, limit]]) splits the separator into an array of strings. If delimited with an empty string, the separator is split between UTF-16, destroying the two UTF-16 encoded characters
  • The toString () rewrite the Object. The prototype. ToString
  • Trim (), trimStart(), trimEnd()
  • ValueOf () Overrides object.prototype.valueof
  • STR [symbol.iterator]() returns an iterator object

RegExp

Regular Expressions is a string used to match a pattern

Literals and constructors

Literals represent arguments between two slashes, without quotation marks. The expression can only be arguments to a constant constructor, either with slashes or quotation marks, and can contain variables

let re = /ab+c/i; // literal notation
let re = new RegExp('ab+c', 'i') // constructor with string pattern as first argument
let re = new RegExp(/ab+c/, 'i') // constructor with regular expression literal as first argument (Starting with ECMAScript 6)
Copy the code

The constructor

/pattern/flags
new RegExp(pattern[, flags])
RegExp(pattern[, flags])
Parameters
Copy the code

Patten is the regular expression text, flag is used to guide the matching process, and can be set

  • G (global match) finds all matches instead of finding one and stopping
  • I (ignore case) If flaguIf yes, case is ignored
  • M (multiline) will start and end symbols (^ and $) works as multiple lines, that is, matches the beginning and end of each line, not the beginning and end of the entire input
  • S (” dotAll “).Match \n, \ R, \u2028 or \u2029, otherwise cannot match
  • U (Unicode) uses patterns as a series of Unicode code points to identify code points larger than 2 bytes
Test ('\uD83D\uDC2A') // true /^\uD83D/u.test('\uD83D\uDC2A'Copy the code
  • Y (sticky) matches only from lastIndex, not from subsequent indexes, e.g
var str = '#foo#'; var regex = /foo/y; regex.lastIndex = 1; regex.test(str); // true (sticky = 1) regex.lastindex = 5; regex.test(str); // false (the lastIndex is considered to be sticky, thus causing a match failure) regex.lastindex; // 0 (reset after match failed)Copy the code

Static attributes

  • Symbol.species returns the default constructor for the re constructor, which subclasses can override
class MyRegExp extends RegExp { // Overwrite MyRegExp species to the parent RegExp constructor static get [Symbol.species]() { return RegExp; }}Copy the code
  • LastIndex, set when g or y modifiers are used, represents the next subscript to start matching, and is set to 0 when exec() or test() finds no strings to match

Instance attributes

  • Regexp.prototype. flags A string containing all flags
  • RegExp.prototype.dotAll
  • RegExp.prototype.global
  • RegExp.prototype.ignoreCase
  • RegExp.prototype.multiline
  • RegExp.prototype.sticky
  • RegExp.prototype.unicode
  • RegExp. Prototype. source returns the expression text, i.e\ \Content between

Regular grammar

A single character
  • . Has the following meaning in ES2018sModifiers allow matching of newlines
    • Represents any single character other than the newline character (\n, \r, \u2028 or \u2029)
    • In character sets (character sets surrounded by parentheses), only literals are represented
  • \d matches any number, equivalent to [0-9]
  • \D non-numeric, equivalent to [^0-9]
  • \w Any alphanumeric and underscore, equivalent to [A-za-z0-9_]
  • \W η›Έε½“δΊŽ[^A-Za-z0-9_]
  • \s Matches single Spaces, including space, TAB, Form feed, line feed, and other Unicode Spaces, Equivalent to [\f\n\r\t\v\ u00A0 \ U1680 \ U2000 -\u200a\ U2028 \u2029\u202f\ U205f \u3000\ufeff]
  • \ S not Spaces
  • \ XHH uses two hexadecimal digits matching characters
  • \ uHHhh uses four UTF-16 matches
  • \u{HHHH} or \u{HHHHH} can only be useduModifier
The border
  • ^ Match the start of the input, if anymModifiers also match characters immediately following newlines
  • $matches the end of the input, if anymThe modifier also matches the character before the newline
  • \b Matches word boundaries and represents a position that has no characters before or after it, such as between letters and Spaces. Note that the length of the word boundary is 0
  • \B Matches a non-word boundary, indicating a position that is either preceded or preceded by words or non-words
Assert forward or backward
  • x(? =y), matches x that follows y
  • x(? ! Y) backward negative assertion, matches x that does not follow y
  • (? <=y)x asserts forward to match x followed by y
  • (?
Grouping and interval
  • Matching x | y x or y
  • [xyz] or [A-C] character set that matches any of the characters. The value can be a hyphen
  • [^ xyz] or [^ a – c]
  • (x) captures the group, matches x and remembers the match. A regular expression may have multiple capture groups, which are saved in the order in which the left parentheses appear, and can be accessed by subscript [n] or $n, where n is a positive integer
  • \n n is a positive integer representing the number of substrings in the capture group, such as /apple(,)\sorange\1/ matches “apple, orange,” in “apple, orange, cherry, peach”.
  • (?

    x) Name the captured x group as Name
  • \k

    references the capture group by Name, such as /(? \w+), yes \k/ matches “Sir, yes Sir” in “Do you copy? Sir, yes Sir!”
  • (? :x) non-capture group, using parentheses but not capturing the capture group
Number of repetitions
  • X times 0 or multiple times
  • X plus 1 or multiple times
  • x? 0 or 1
  • X {n} n times
  • X {n,} n is a positive integer, at least n times
  • X {n,m} at least n and at most m times
  • Add after the number?, such as x *? The default is greedy match, try to match as many characters, plus a question mark will not greedy

escape

If you want to use any special characters, you need to use \ escape

The specific use

This includes the exec and test methods for RegExp and the match, replace, search, and split methods for String

To find out if they match, use test or search, you need to know more. Use exec or match,replace to replace child elements, and split to separate strings

  • Regexobj.test (STR) checks for matches and returns a Boolean value
  • Str.search (regexp) returns the subscript of the first match, -1 if not found, or regexp if the argument is not regular
  • Regexobj. exec(STR) performs a search, returning either an array of results (with additional index and input attributes) or NULL, where the 0th item in the array is the complete matching string, the others are sequential capture groups, and index is the subscript of the matching string.
  • Str.match (regexp) returns null if no match is reached, depending on the G modifier.
    • If g is used, all complete matches are returned, with no additional attributes
    • If not, only the first full match is returned, with the following additional attributes
      • Groups A capture group, undefined if none is returned
      • index
      • input
  • Str.matchall (regexp) must have a G modifier that returns an iterator equivalent to an array of the results of multiple global exec executions
const regexp = /t(e)(st(\d?) )/g; const str = 'test1test2'; const array = [...str.matchAll(regexp)];Copy the code
  • Const newStr = STR. Replace (regexp | substr, newSubstr | function), respectively
    • Regexp A re, and the matched character is replaced with a new string
    • The first occurrence of substr is replaced
    • NewSubstr the substring to be replaced, which can contain the following replacement patterns
      • $insert a ‘insert a’
      • $& inserts the matching substring
      • $’ inserts the content to the left of the currently matched substring
      • $’ inserts the content to the right of the currently matched substring
      • $n indicates the NTH capture group
      • The $group name
    • Function The function that creates a new substring, called once for each match of the global pattern, with arguments respectively
      • Match is the equivalent of $&
      • p1,p2, … The equivalent of $n
      • offset index
      • string input
      • NamedCaptureGroup Names the capture group
  • Const newStr = STR. ReplaceAll (regexp | substr, newSubstr | function) to replace all matching to a child of the characters, g must be used
  • Str.split ([separator[, limit]]) groups the string according to separator, and the separator itself is removed and represented separately
    • Separator Separator position. It can be a string or a re
    • Limit Returns the maximum length of the array

Now that this section is over, go to the COMPLETE ES2021 Features (2) and read the rest!