Writing in the front
- The language is simple and easy to use, but its mechanics are so complex and subtle that even experienced JavaScript developers can’t really understand it without studying it. This set of books addresses the current trend of uncomprehending JavaScript developers, provides an in-depth understanding of the internal mechanics of the language, and provides a comprehensive introduction to important knowledge points in JavaScript that are often misunderstood and overlooked.
- My quick review: The JavaScript you Don’t Know is part one, part two, and this is part two of the ES6-related series. In my opinion, the first volume is well written, the middle volume is a bit redundant, and the second volume is rough on ES6. However, there is a somersault, or more or less some harvest.
- !!!!! At the end of the article there are PDF books, notes mind map, with the book code package download address, please help yourself! To read all notes in the book Intensive Series, please move: Recommended favorites -JavaScript Book Intensive Notes Series navigation
Chapter 1 ES? Present and future
- Unlike ES5, ES6 doesn’t just add a new set of apis to the language. It includes a new set of grammatical forms, some of which may take some time to understand and become familiar with. It also includes a variety of new organizational forms and new helper apis for manipulating various data types
1.2. Transpiling
- Transpiling (Transformation +compiling, Transformation +compiling) technology. In a nutshell, the idea is to use specialized tools to convert your ES6 code into equivalent (or approximate) code that works in an ES5 environment
- Not all new ES6 features require transpiler, but there is also a pattern called Polyfill (also known as SHIM). Where possible, Polyfill defines the equivalent behavior in the old environment for the behavior in the new environment. Syntaxes cannot polyfill, whereas apis generally can
Chapter 2 Grammar
2.1. Block scope declaration
- The basic unit of variable scope in JavaScript has always been function. If you need to create a block scope, the most common method, in addition to plain function declarations, is to call function expressions (IIFE) immediately.
- Let declarations: You can create declarations that bind to any block. Just a couple of {.. } creates a scope; This ReferenceError caused by prematurely accessing a reference to a LET declaration is technically called a temporary dead zone error (TDZ)– you are accessing a variable that has been declared but not initialized; Variables that are not assigned when declared are automatically assigned to undefined, so let b; Let b = undefined; Undeclared variable, so typeof is the only safe way to check if it exists; Why DO I insist that all LET declarations should be placed first in their scope, thus completely avoiding the problem of accidental premature access?
- Const declaration: const, used to create constants; It is a variable that is read only after an initial value is set; Const declarations must be explicitly initialized; If the value is complex, such as an object or array, its contents can still be modified; If const is used, in theory, it is easier for the engine to understand that the value/type of this variable never changes, so it can cancel some possible tracing;
- Block-scoped functions: Starting with ES6, functions declared within a block are scoped within that block
2.2. Spread/rest
- When… When used before an array (any iterable, really), it “expands” the variable into individual values
- . The other common use of “can be seen basically as reverse behavior; . Collect a series of values together into an array
2.3. Default Parameter values
- Probably one of the most common JavaScript tricks involves setting default values for function arguments
- You can only omit the last number of arguments (for example, the last) by passing in fewer than “expected” arguments, not those in the middle or at the beginning of the argument list
- An important JavaScript design rule to remember is that undefined means missing. That is, undefined and missing are indistinguishable, at least as far as function parameters are concerned
- Default value expressions: Default value expressions are lazy-evaluated, which means they are run only when needed — that is, when the parameter value is omitted or undefined; Prototype is an empty Function with no operations;
2.4. Deconstruction
- You can think of manual assignment of indexed values in an array or object property as structured assignment. Special syntax for array and object deconstruction
- Not just declarations: You should not mix declarations in assignments unless you need to treat all assignment expressions as declarations. Otherwise there will be syntax errors
- Repeated assignment: Object destruction allows listing the same source property multiple times (holding any value type); Remember: The purpose of deconstruction is not just to type less, but to read more;
2.5. Too much, too little, just right
- If more values are assigned than the deconstructed/decomposed value, the extra value is assigned undefined as expected
- Default value assignment: Either form of destruction can provide a default value for assignment, using the = syntax similar to the default function parameter values above
- Nested deconstruction: You can think of nested deconstruction as a simple way to expand an object’s namespace
- Destruct arguments: Destruct assignments/defaults are placed in the argument list, and the recombination process is placed in the return statement of the function body
2.6. Object literal extension
- Simple properties
- Concise approach: Strictly speaking, ES5 defines getter/setter literal forms, but they are not used much, mainly due to the lack of transpiler to handle this new syntax (in fact, the only major new syntax added to ES5)
- Computed property names: Object literals that define the position of property names
[...]
Can place any legal expression; The most common use for calculating property names is probably with Symbols; - set
[[Prototype]]
- Super object
2.7. Template literals
- The name of this feature is very misleading and depends on your understanding of the word template
- Newlines (newlines) inserted in string literals are preserved in the string value
- Insert expression: in the insert string literal ${.. } can be any valid expression, including function calls, online function expression calls, and even other insert string literals; An insert string literal is in the lexical scope in which it appears, without any kind of dynamic scope;
- Tag template literals: Rename this feature to explicitly express its functionality: tag string literals; Which practical applications (to format numbers in dollar notation; Other applications include special handling of globalization, localization, etc.)
2.8. Arrow functions
- Arrow function definitions include a list of arguments (zero or more arguments, or (..) if there is more than one argument). Enclosing), followed by the identifier =>, and the function body comes last
- Arrow functions are always function expressions; There is no arrow function declaration
- Arrow functions are anonymous function expressions — they have no named references for recursion or event binding/unbinding
- I think the readability of the => arrow function conversion is inversely related to the length of the converted function. The longer the function, the smaller the benefit of =>; The shorter the function, the greater the benefit of =>
- Not just shorter syntax, but this: Right
= >
Most of the concern with function, return, and {.. } saves those precious keyboard inputs; right= >
Most of the concern with function, return, and {.. } saves those precious keyboard inputs; Inside the arrow function, the this binding is not dynamic, but lexical; Bottom line:= >
Is a lexical binding for this, arguments, and super. This ES6 feature is designed to fix common problems, not bugs, coincidences, or errors
2.9. The for… Of circulation
- for.. The value of the of loop must be an iterable, or it must be able to convert/box the value of an Iterable object. Iterable is an object that produces iterators for use in loops
- Standard built-in values for iterable in JavaScript by default (or provided) include: Arrays, Strings, Generators, Collections/TypedArrays
- for.. An of loop can also terminate prematurely with a break, continue, return (if in a function), and throw an exception
2.10. Regular expressions
- One fact: Regular expressions in JavaScript have remained essentially unchanged for a long time
- Unicode identifiers: Prior to ES6, regular expressions could only be matched based on PMB characters, meaning that those extended characters were matched as if they were two separate characters; In ES6, the U identifier represents a regular expression that interprets a processing string using Unicode (UTF-16) characters, matching such an extended string as a single entity; What affects is the length of the matching part; It is also important to note that the U identifier allows quantifiers like + and * to apply the entire Unicode code point as a single character, not just to the low level of the character (that is, the right-most part of the symbol);
- Fixed point identification: Another new label pattern in ES6 regular expressions is Y, often referred to as “sticky”. Fixed point refers to a virtual anchor point at the beginning of the regular expression, and matches only from the position specified by the lastIndex attribute of the regular expression.
- Flags: Before ES6, to examine a regular expression object to determine which flags it applied, you had to parse it out from the contents of the source attribute. In ES6, you can now get these values directly using the new Flags attribute; Another tweak in ES6 is to pass the identifier to an existing regular expression, RegExp(..). Constructors now support flags;
2.11. Number literal extension
- Although numbers can be specified in different base forms, the numeric value of a number is still the saved value, and the default output interpretation is always decimal
2.12. The Unicode
- Unicode characters range from 0x0000 to 0xFFFF and contain all the standard printed characters (in various languages) that you might see and touch. This set of characters is called the basic multilingual plane (BMP). BMP even contains funny symbols like snowman
- There is now a new form that can be used for Unicode escape (in strings and regular expressions), called Unicode codepoint escape
- Unicode-enabled characters: By default, JavaScript string operations and methods are not aware of the String Russian astral symbol; How exactly to calculate such a string length.
[...gclef].length
- Character positioning: The native ES6 answer to this is charAt, but does not support atomicity of Astral characters, nor does it factor in combined symbols; ES6 provides codePointAt; An easier and better way to get A Unicode-enabled charAt by combining String.fromCodePoint and codePointAt;
- Unicode identifier name
2.13. Symbols
- ES6 introduces a new native type for JavaScript: Symbol. Unlike other primitive types, symbol has no literal form
- Note the following: New cannot and should not be used for Symbol(). It is not a constructor and does not create an object; The argument passed to Symbol() is optional. If passed in, it should be a string that gives a user-friendly description of the symbol’s purpose. The output of typeof is a new value (“symbol”), which is the preferred way to identify symbols;
- The internal value of the symbol itself — called its name — is not present in the code and is not available. You can think of this symbolic value as an automatically generated (within the application) unique string value
- The main point of the symbol is to create a string-like value that does not conflict with any other value
- If you want to use the symbol value as a real String, then it needs to be explicitly typed with String() or toString(), because it is not allowed to implicitly convert the symbol to a String
- Symbol registration: symbol.for () searches the global Symbol registry to see if any Symbol with the same description already exists and returns it if so; In other words, the global registry treats the symbol value itself as a singleton in terms of its descriptive text; Ironically, the basic purpose of the notation is to replace the magic string (arbitrary string given special meaning) in the application; You can use symbol.keyfor () to extract the description text (key value) of the registered Symbol;
- Symbol as an attribute of an object: If a symbol is used as an attribute/key value of an object, it is stored in such a way that the attribute does not appear in the general attribute enumeration of the object; To obtain Object symbol attribute, use the Object. The getOwnPropertySymbols;
2.14 summary
- Most of these new syntactic forms are designed to eliminate the pain points of common programming tricks, such as setting default values for functions and collecting the “rest” of parameters into arrays
- And like
= >
Features like the arrow function appear to be designed to make code more syntactically concise, but it actually has very specific behavior properties and should only be used when appropriate
Chapter 3 code organization
3.1. The iterator
- An iterator is a structured pattern for extracting data from a source, one at a time
- An iterator is an ordered, continuous, pull-based organization for consuming data
- The IteratorResult interface specifies that the value returned from any iterator operation must be an object of the following form:
{value: .. , done: true/false}
- Next () Iteration: next(..) of the iterator. Methods can take one or more optional arguments. The vast majority of built-in iterators do not take advantage of this feature
- Optional return and throw: Most built-in iterators do not implement the optional iterator interface -return (..) And throw (..) ; return(..) Is defined to send a signal to the iterator that the consumer code is finished and no more values will be extracted from it; throw(..) Used to report an exception/error to the iterator, which may react differently to this signal than to return(..). Completion signal of meaning;
- Custom iterators: This specific usage emphasizes that iterators can be used as a pattern to organize functionality, not just data
3.2. The generator
- ES6 introduces an entirely new and somewhat exotic form of function called generators
- A generator can pause itself in the middle of execution, either immediately or after a period of time. So obviously it’s not guaranteed to finish like a normal function
- Each pause/resume loop during execution provides an opportunity to pass information in both directions, with the generator returning a value and the control code that restores it returning a value
- Syntax: Executing generators, such as Foo (5, 10), does not actually run code in the generator. Instead, it generates an iterator that controls the generator to execute its code; Generators also have a new keyword that can be used within them to indicate pause points: yield; A never-ending loop means a never-ending generator, which is perfectly valid and sometimes exactly what you need; Yield is not strictly an operator, although it does look like one when used like yield 1; yield.. The similarity between the behavior of expression and assignment expression has some conceptual rationality. Because the yield keyword has a low priority, almost yield.. Any subsequent expression is evaluated first and then sent using yield; Like = assignment, yield is “right-associative,” which means that the occurrence of multiple yield expressions in succession is equivalent to using (..) Group from right to left; Yield * can call another generator (by delegating to its iterator), so it can also perform some generator recursion by calling itself;
- Iterator control: An early proposal after ES6 would have access to the original Next (..) passed in via a separate meta-attribute within the generator. Value of the call; Generators can be thought of as value producers, where each iteration produces a value for consumption; In a more general sense, it might make more sense to think of a generator as a controlled, transitive code execution;
- Early completion: Iterators attached to generators support optional return(..) And throw (..) Methods. Both methods have the effect of immediately terminating a paused generator; return(..) In addition to being called manually, it can also be called automatically at the end of each iteration by any ES6 artifact that consumes an iterator, such as for… The of loop and spread operators; The purpose of this feature is to inform the generator that if the control code does not iterate over it, it may perform cleanup tasks (freeing resources, resetting state, etc.); Don’t put yield statements inside a finally clause. While this is valid and legal, it’s a terrible idea. It will delay your return(..) Completion of the call; And return (..) Different, iterator throw(..) Methods are never called automatically;
- Error handling: Generator error handling can be expressed as a try… Catch, which can work both inside-out and outside-in
- Transpile generators: An exercise that reinforces the notion that generators are really a simplified syntax for state machine logic
- Generators use: two main patterns (producing a set of values; Sequential task queue;)
3.3. The module
- Of all the JavaScript code, the single most important code organization pattern is module
- Old approach: The traditional module model is based on an outer function with internal variables and functions, and a “public API” that is returned; The common one is asynchronous module definition (AMD), and the common module definition (UMD).
- Moving forward: For ES6, we no longer rely on wrapper functions and closures for module support; A significant conceptual difference between ES6 modules and the way we’ve handled modules in the past; The ES6 module will provide complete support for code organization, including encapsulation, control of public apis, and reference dependency imports; In the long run, the ES6 module will essentially replace all previous module formats and standards, even CommonJS, because the ES6 module is built on the syntax support of the language; Module transpiler/ conversion tools are essential. Whether you’re writing a generic module, AMD, UMD, CommonJS, or ES6, these tools have to be parsed into a form that works for all the environments in which your code runs;
- New approach: The two main new keywords supporting the ES6 module are import and export; Both import and export must appear in the top-level scope where they are used. They must appear outside all code blocks and functions; Everything that is not marked export remains private within the module scope. There is no global scope within the module; The module can also access window and all “global” variables, just not as the lexical top-level scope; Module exports are not plain assignments of values or references, as you are familiar with the assignment operator =. In effect, what is exported is a binding (similar to a pointer) to these things (variables, etc.); Default export Sets a specific export binding to be the default export when importing a module. The name of the binding is default; Each module can have only one default; The JavaScript engine cannot statically analyze the contents of trivial objects, which means it cannot optimize the performance of static imports. The advantage of having each member exported independently and explicitly is that the engine can statically analyze and optimize it;
- Module-dependent rings: first of all, it must be declared to avoid deliberately designing systems with ring dependencies; Essentially, mutual imports, along with static validation to verify the validity of the two import statements, virtually combine two separate module Spaces (via bindings) so that Foo (..) You can call bar(..) And vice versa; The statically loaded semantics of import statements mean that it is possible to ensure that “foo” and “bar” that depend on each other through import are loaded, parsed, and compiled before either of them can be run;
- Module loading: The import statement uses a separate mechanism provided by the external environment (browser, Node.js, etc.) to actually parse the module identifier string into usable instructions for finding and loading the desired module. This mechanism is the system module loader; If in a browser, the default module loader provided by the environment resolves the module identifier into a URL. If on a server like Node.js it is resolved to a local file system path; The module loader itself is not specified by ES6. It is a separate, parallel standard currently managed by the WHATWG Browser Standards Working Group;
Class 3.4.
- Class: At the heart of the new ES6 class mechanism is the keyword class, which represents a block whose contents define the members of a function prototype; The ES6 class is not a real entity in itself, but rather a meta-concept that wraps around other concrete entities such as functions and attributes and combines them together;
- Extends and super: ES6 also provides a syntactic sugar to create between two function prototypes through the common class-oriented term extends
[[Prototype]]
Delegate chaining – often mislabeled “inheritance” or confusingly labeled “archetypal inheritance”; In the constructor, super automatically points to the “parent constructor” and in the method, super points to the “parent object” so that its properties/methods can be accessed. - New.target: a new concept called a meta-attribute; New target is a new “magic” value that is available in all functions, although it is usually undefined in general functions; In any constructor, new.target always points to the constructor that new actually calls directly, even if the constructor is in a parent class and uses super(..) through the subclass constructor. Delegate invocation; The new. Target meta-attribute in the class constructor has little use other than to access static/methods;
- Static: Added directly to the function object of this class, not to the prototype object of this function object
3.5 summary
- Iterators provide sequential access to arrays or operations. You can do it through images
for.. of
and.
These new language features consume iterators - Generators are functions that support local pause/resume. Control through iterators. They can be used programmatically (also interactively, through
yield/next
Message passing) generates values for iteration consumption - Modules support private encapsulation of implementation details and provide a public export API. Module definitions are file-based singleton instances that are statically resolved at compile time
- Class provides a clearer syntax for prototype-based coding. The new super has also been resolved
[[prototype]]
The thorny issue of relative references in chains
Chapter 4 asynchronous flow control
- The main mechanism for managing asynchrony has always been function callbacks
- ES6 has added a new feature to help address the serious drawback of using callback only for asynchrony: Promise
4.1. Promise
- Introduction: Some misconceptions: Promises are not a replacement for callbacks. Promise provides a reliable intermediate mechanism for managing callbacks between the callback code and the asynchronous code that will perform the task; Promises can be linked together, which strings together a series of steps that are completed asynchronously; The Promise chain provides an approximate asynchronous flow of control; Another way to define a Promise is to think of it as a future value, a wrapper that deserves to be independent of time; In other words, a Promise can be thought of as an asynchronous version of the value returned by a synchronous function; There are only two possibilities for the outcome of a Promise resolution: complete or reject, with an optional single value; Promises can only be made (fulfilled or rejected) once;
- Construct and use promises: Supply the constructor Promise(..) Both arguments to are functions, commonly called resolve(..). And reject (..) ; Promise has a then(..) Method that takes one or two callback functions as arguments; The default success callback passes the completion value, and the default error callback passes the rejection reason value. If never pass then(..) Or catch (..) To observe, it will remain unprocessed;
- Thenable: Promise (..) A real example of a constructor is Promise. But there are other promise-like objects, called Thenable, that can also be interpreted by the promise mechanism in general; Any information provided by then(..) The object (or function) of a function is considered thenable; As a general rule, if you receive something from another system that calls itself a Promise or Thenable, you shouldn’t blindly trust it; Avoid using a value that might be mistaken for thenable directly for the Promise mechanism;
- Promise API: The Promise API also provides static methods to work with Promises; Promise.resolve(..) Creates a promise with a resolution to the incoming value; resolve(..) And Promise. Resolve (..) Can accept the promise and accept its status/resolution, while
reject(..)
andPromise.reject(..)
There is no distinction between what values are received;Promise.all([..] )
Wait for everything to be done (or the first rejection) whilePromise.race([..] )
Wait for the first to complete or reject;Promise.all([])
Will complete immediately (no completion value),Promise.race([])
Will be suspended forever. Therefore, it is recommended that you never use these methods with empty arrays;
4.2. Generator +Promise
- This important pattern needs to be understood: a generator can yield a promise, which can then be bound to resume the generator with its completion value
- Promises are a reliable system that reverses normal callbacks or chunk reversals of control
- Combining the Promise’s trusted caprices with the generator’s synchronized code effectively addresses all of the important shortcomings of callbacks
- Essentially, whenever flow control logic occurs in code with more than two asynchronous steps, a promise-yield generator driven by the Run tool can and should be used to express control flow in an asynchronous style
4.3 summary
- ES6 added promises to address one of the main shortcomings of callbacks: the lack of guarantees for predictable behavior. Promises represent future completion values from potentially asynchronous tasks, normalizing behavior across synchronous and asynchronous boundaries
- Promise’s combination with generators completely rearranges asynchronous flow control code to eliminate the ugly callback stew (or hell)
Chapter 5 Collection
- A Map is like an object (key/value pair), but instead of having a string key value, it can use any value – even another object or Map
- A Set is like an array (a sequence of values), but the values are unique; If the new value is duplicate, it will be ignored.
- There are also corresponding weak (memory/garbage collect-related) versions: WeakMap and WeakSet
5.1. TypedArray
- In fact, typed arrays are more about structuring access to binary data using array-like semantics (indexed access, etc.)
- Small side: It is important to understand that arR maps to the small side Settings (big or small) of the platform on which JavaScript is running; The size side means whether the lower byte (8 bits) in a multi-byte number (such as the 16-bit unsigned integer created in the previous code snipple) is to the right or left of the number byte representation; The most commonly used representation on the Web today is the small-endian approach, but there are certainly browsers that don’t;
- Multiple views: A single buffer can be associated with multiple views
- Classed Array constructor: Instances of a classed array constructor look almost exactly like normal native arrays. Some differences include having a fixed length and having values of a “type”; TypedArray cannot be used with unreasonable array. prototype methods such as modifiers (
splice(..)
,push(..)
, etc.) andconcat(..)
; Note that TypedArray German elements are limited to the size of the declared bits; To address the limitations of square overflow, you can useTypedArray.from(..)
Functions;
5.2. The Map
- Understanding objects is creating unordered key/value pair data structures, also known as mappings
(map)
The main mechanism of - The main disadvantage of objects as maps is that you cannot use non-string values as keys
- The only drawback is that you can’t set and get values using square brackets [] syntax, but you can
get(..)
andset(..)
Method perfect substitute - The Map values
- Map keys: The essence of a Map is to allow you to associate some additional information (values) with an object (key) without putting that information into the object itself; For maps, we usually use objects, although any type of value can be used as a key, because strings and other primitive types can already be used as a key for ordinary objects;
5.3. WeakMap
- WeakMap is a variant of Map and most of the external behavior is the same. The difference lies in the way the internal memory allocation (especially its GC) works
- WeakMap (only) accepts objects as keys. These objects are weakly held, meaning that the item in WeakMap is removed if the object itself is garbage collected
- WeakMap has no size attribute or clear() method, and does not expose any iterators on keys, values, or items
- It is important to note that WeakMap only weakly holds its key, not its value
5.4. The Set
- A set is a set of values that are unique (duplicates are ignored)
- In addition to treating negative 0 as the same as zero,
has(..)
The comparison algorithm andObject.is(..)
Almost the same as - Set iterators: The inherent uniqueness of a Set is its most useful property; The uniqueness of a set does not allow casting, so 1 and “1” are considered different values;
5.5. WeakSet
- Just as WeakMap weakly holds its key (strongly holds its value), WeakSet weakly holds its value (there is no key).
- WeakSet’s value must be an object, not a primitive value like set
5.6 summary
- TypedArray provides “views” of various integer types for binary buffers, such as 8-bit unsigned integers and 32-bit floating-point types. Array access to binary data makes operations easier to express and maintain, making it easier to manipulate complex data such as video, audio, canvas data, and so on
- A Map is a key/value pair where the keys are not just strings/primitives, but also objects. Set is a unique list of member values (of any type)
- WeakMap is also a map where the key (object) is weakly held, so when it is the last reference to the object, the GC (garbage collection) can reclaim the item. WeakSet is also a set, where a value is weakly held, meaning that GC can remove it if the item in it was the last reference to the object
Chapter 6 added apis
6.1. Array
- One of the most extended features of the various JavaScript user libraries is the Array type
- 1. Static function array.of (..) : Array (..) A well-known pitfall of constructors is that if you pass in only one argument and the argument is a number, instead of constructing an array of single elements with the value of that number, you construct an empty array with the length attribute of that number
- 2. Static function array.from (..) An array-like object in JavaScript is an object that has a length property, specifically an integer value greater than or equal to 0. Common requirements is to put them into real Array, Array. Prototype. Slice. The call (arrLike); New ES6 Array. The from (..) Methods are better understood, more elegant, more concise alternatives;
- 3. Create arrays and subtypes: of(..) And from (..) Both use constructors that access them to construct arrays
- 4. Prototype method copyWidthin(..) : Array. CopyWithin (..) Is a new modifier method, supported by all arrays; It copies a portion of an array to another location in the same array, overwriting all the original values of that location; copyWithin(..) Method does not increase the length of the array. At the end of the array copying stops;
- 5. Prototype method Fill (..) : Fills an existing array completely (or partially) with the specified value; Optional accept arguments start and end, which specify the location of the subset to populate the array;
- 6. Prototype method find(..) The most common way to search an array is always indexOf(..). Method, which returns the index of the value found, or -1 if no value is found; indexOf(..) Need to match === strictly; ES6 find (..) Once returned to true/ true, the actual array value is returned;
- 7. Prototype method findIndex(..) IndexOf (..) is used if strictly matched index values are required. If you need to customize the matching index value, use findIndex(..).
- 8. Prototype methods Entries (), values(), keys() : It provides the same iterator methods entries(), values() and keys(), and is a collection in that sense
6.2. The Object
- 1. Static function Object.is(..) : static function object.is (..) Perform value comparisons more strictly than the === comparison; Object.is(..) Call the underlying SameValue algorithm; Object. Is (..) should be selected if NaN or -0 is strictly identified. ;
- 2. Static function Object. GetOwnPropertySymbols (..) It gets all symbolic properties directly from the object
- Static function Object.setProtoTypeof (..) : sets the object
[[Prototype]]
Used of behavioral delegation - 4. Static function Object.assign(..) Many JavaScript libraries/frameworks provide tools for copying/mixing properties from one object into another; ES6 added object.assign (..) For each source, its enumerable and own (that is, not “inherited”) key values, including symbols, are copied by simple = assignment; Non-enumerable attributes and non-own attributes are excluded from the assignment process; Object.create(..) ES5 tool. Create one
[[Prototype]]
Linked empty objects;
6.3. Math
- Perform these calculations more optimally, or perform more precise calculations than the manual version
6.4. The Number
- The two new additions are references to existing global functions: number.parseint (..) And the Number. ParseFloat (..)
- 1. Static properties: added some auxiliary numeric constants: number. EPSOLON, number. MAX_SAFE_INTEGER, and number.min_safe_INTEGER
- 2. Static attribute number.isnan (..) : standard global utility isNaN(..) Flawed since its inception, it returns true for everything that isn’t a number, not just true NaN values, because it casts arguments to numeric types (which may mistakenly result in NaN). ES6 adds a correction tool called Number.isnan that works as expected
- 3. Static attribute number.isFinite (..) : Standard global isFinite(..) The parameter is cast, but number.isFinite (..) That compulsion will be omitted
- 4. Integer dependent static functions: JavaScript numeric values are always floating point (IEE-754); X === math.floor (x), ES6 adds number.isINTEGER (..) ; JavaScript code itself will not run faster by using only integers, but the engine can only use optimization techniques (such as ASM.js) if integers are used;
6.5. The string
- 1.Unicode functions: string.fromcodePoint (..) , String. CodePointAt (..) And the String. The normalize (..) These functions are added to improve JavaScript string values uiUnicode support; String prototype method normalize(..) Used to perform Unicode canonicalization, or to concatenate characters with “merge” characters, or to unbind merged characters;
- 2. Static function String.raw(..) : String. Raw (..) The utility is provided as a built-in tag function, used with template string literals to get the raw string without any escape sequences applied
- 3. Prototype function repeat(..) : Repeated string
- 4. String checking functions: 3 new methods for searching/checking: startsWidth, endsWidth and includes
Chapter 7 metaprogramming
Writing in the front
- Metaprogramming is programming in which the object of operation is the behavior of the program itself. In other words, it is the programming of the program
- Metaprogramming is concerned with code that looks at itself, code that changes itself, and code that changes default language features in order to affect other code
- The goal of metaprogramming is to make the rest of the code more descriptive, expressive, and flexible by leveraging the introspection of the language itself
7.1. Function name
- By default, the name attribute is not writable but configurable, meaning object.defineProperty (..) can be used if needed. To manually modify
7.2 yuan properties
- Meta-attributes provide special meta-information that cannot be obtained by other methods in the form of attribute access
- With all metaprogramming techniques, be careful not to write code that is too clever for future maintainers or you to understand
7.3. Open symbols
- In addition to defining symbols in your own programs, JavaScript predefines some built-in symbols, called public symbols
- Iterator represents a specific location (property) on any object, and the language mechanism automatically looks for a method at that location that constructs an iterator to consume the value of that object
- One of the most common metaprogramming tasks is to do introspection on a value to figure out what kind it is, usually to determine what kind of operation is appropriate to perform on it. The most common introspection techniques are toString() and Instanceof
- The @@species symbol, which controls which constructor the class’s built-in methods use when generating new instances
- The abstract conversion operation ToPrimitive is used when an object must be cast to a native type for an operation. Prior to ES6, there was no way to control this behavior
- In ES6, the symbol @@Toprimitivesymbol as an attribute on any object value can customize this ToPrimitive cast by specifying a method
- For regular expression objects, there are four public symbols that can be overridden: @@match, @@search, @@split, and @@replace
- Symbol @ @ isConcatSpreadable can be defined as any object of Boolean attribute (Symbol. IsConcattSpreadable), used to indicate if you pass it to an array of concat (..) Whether it should be expanded
- The Symbol @@unscopables can be defined as the object property of any object (symbol.unscopables) and is used to indicate which properties can or can be exposed as lexical variables when using the with statement
- The WITH statement is not allowed in strict mode and should therefore be considered an outdated feature of the language. Don’t use it
7.4. The agent
- One of the most obvious metaprogramming features added to ES6 is the Proxy feature
- A proxy is a special object that you create that “wraps” — or stands in front of — another ordinary object
- Proxy limitations: a broad set of basic operations that can be performed on objects can handle function traps through these metaprogramming; Agents always have some invariant, that is, behavior that cannot be overridden; These immutability limits the ability to customize proxy behavior, but their purpose is to prevent you from creating weird or unusual (or inconsistent) behavior;
- Cancelable proxy: You want to create a proxy that can be deactivated when you want to stop it as a proxy. The solution is to create a cancelable proxy; Revocable Proxy (..) Create, which is a normal function, unlike Proxy(..) One is a constructor; Once the cancelable agent is cancelled, any access to it (any trap that triggers it) raises TypeError; One possible use scenario for detractable proxies is to distribute proxies to a third party in your application that manages your model data rather than giving references to the real model itself;
- Using a proxy: The proxy becomes the primary object of code interaction, while the actual target object remains hidden/protected
7.5. Reflect the API
- The Reflect object is a trivial object (like Math), not a function/constructor like the other built-in primitives
- It holds static functions corresponding to various controllable metaprogramming tasks
- One difference is that if the first argument (the target Object) is not an Object, the Object.* tool will try to type it into an Object
- Reflect’s metaprogramming capabilities provide programming equivalents that simulate various syntactic features, exposing previously hidden abstractions. You can leverage these capabilities to extend functionality and apis to implement domain-specific languages (DSLS)
- Property sorting: Prior to ES6, the listing order of an object’s keys/properties was implementation-dependent and not defined in the specification; For ES6, the listing order of owning attributes is determined by
[[OwnPropertyKeys]]
Algorithmically defined; Its order is (first, in ascending order, enumerate all integer index attributes; Then enumerate the remaining string property names in the order they were created; Finally, enumerate the owned symbol properties in the order they were created;)
7.6. Characteristic test
- A feature test is a test that you run to determine whether a feature is available or not
- The most common feature test in JavaScript is to check if an API exists and, if not, define a polyfill
7.7. Tail recursive calls
- Normally, when a function is called from within another function, a second stack frame is allocated to independently manage the variables/functions of the second function call
- When considering recursive programming (a function that calls itself repeatedly) – or two or more functions that call each other recursively – the depth of the call stack can easily reach hundreds or thousands, or even more
- JavaScript engines have to set arbitrary limits to prevent this programming technique from causing browsers and devices to run out of memory and crash. “RangeError: Maximum Call Stack Size exceeded”
- The call stack depth limit is not controlled by the specification. It is implementation-dependent and varies by browser and device
- Tail Call Optimization (TCO) – Additional stack frame allocation is not required. The engine does not need to create a new stack frame for the next function call, just reuse the existing stack frame
Chapter 8 after ES6
- Transpiler and Polyfill were our Bridges to migrate to new features that had not been implemented by all browsers that needed to support them
8.1. Asynchronous functions
- Async function is essentially generator +Promise+run(..) Grammatical sugar for patterns; They all work the same way at the bottom
- Warning: Async Function has an unresolved problem because it only returns a promise, so there is no way to cancel a running instance of Async Function externally; Promises are non-cancelable (at least at the time of writing);
8.2. The Object. Observe
- Perhaps later in ES6, we’ll see this via the tool Object.observe(..). Support added directly to the language.
- Essentially, the idea is that you can set up a listener to watch for changes in an object and then call a callback each time the change occurs
- There are six types of changes that can be observed: Add, Update, Delete, Reconfigure, setPrototype, preventExtensions
- 1. Custom change events: In addition to the previous six types of built-in change events, you can also listen for and emit custom change events
- 2. End the observation
8.3. Power operators
- There is a proposal to add an operator for JavaScript to perform exponents, like math.pow (..) The same
8.4. Object properties and…
- . The use of operators to expand and collect arrays is straightforward, but what about objects
8.5. Array# includes
- A well-supported proposal has emerged to add an array search method that truly returns a Boolean value, including (..)
- Array.includes(..) The matching logic used can find Nan values, but cannot distinguish -0 from 0
8.6. SIMD
- The SIMD API exposes a variety of low-level (CPU) instructions that can operate on multiple numeric values simultaneously
8.7. WebAssembly (WASM)
- One of the biggest pressures in recent (and near future) design changes to the JavaScript language is the need to be a better target language for transformation/cross-compilation from other languages (e.g. C/C++, ClojureScript)
- Asm.js is a subset of legal JavaScript that most strictly limits the behavior that makes it difficult for JavaScript engines to optimize. As a result, asM.js-compatible code running on an ASM-enabled engine is vastly more efficient than its native-optimized equivalent C program
- WASM proposes a highly compressed AST (syntax tree) binary representation of code that can then be directed to a JavaScript engine, with an infrastructure that does not need to be parsed through JavaScript or even conform to JavaScript rules
Write in the back
- PDF books, notes a mind map, along with the book code package download address: pan.baidu.com/s/1ei5ya29O… (Extraction code: DCQO)
- Purchase address: u.jd.com/FwSmuH (it is recommended to buy paper books to study)