A variable and scope
1) Let, const, block-level scope, and variable declarations
Variables declared by lets are valid only in the block they are in; Let declared variables can solve the problem of using var and for loops to get the latest variable values (traditionally, closures were needed to solve this problem); Variables declared by let do not have variable promotion (from undefined->ReferenceError, which is actually a temporary dead zone), cause temporary dead zones of variables (it cannot be used before declaring let variables), and do not allow repeated declarations;
Const declares variables that behave like lets, only more soThere are two stronger constraints: 1. 2. Note that the memory address of the declared variable cannot be changedFor const primitive types, the value is stored in the memory address, meaning that the variable cannot be reassigned. For an object declared as const, the object’s content can still be changed, but its reference cannot be changed. (Freeze objects should be object.freeze ())
From ES5’s global and functional scopes to ES6’s added block-level scopes, one wonders why block-level scopes were introduced. In order to solve the problem of the existing mechanism, the programmer invented the anonymous instant execution function to simulate the block-level scope. Example: the inner scope overwrites the variables of the outer scope, and the variables of the inner scope run into the outer scope.
There are 6 ways to declare variables: var function let const import class
The global variables declared by var function are attributes of the top-level object. But the global object declared by let const class is not a property of the top-level object.
3) Deconstruction of assignment (according to a certain structure to parse out the assignment)
Use scenarios for destructuring assignment: quick variable assignment, data extraction, function parameter definitions and default values, traversing a structure
What kind of data can be deconstructed and assigned? — Any data type that has an Iterator interface. Common types of destructively assigned data are arrays, objects, strings, bools, and numbers. Null and undefined cannot be destructively assigned
The deconstructing assignment process can specify default values
Method extensions for two native objects
1) String
Improved Unicode support, string traversal support (which we’ll see later actually deploys the iterator interface), support for methods like repeat(), template strings
2) RegExp
The first argument to the constructor is a regular expression, specifying that the second argument is no longer an error, the U modifier, the y modifier, or the S modifier
3) Number
New binary and octal notation, new method parseInt(), number.epsilon minimal constants, safe integers, new Math method
4) Function
Function parameter defaults, REST parameters, strict mode inside the function, function name attribute, arrow function
5) Array
Extended operators…
6) Object and Symbol
(1) the Object
Support shorthand: the same attribute k-v can be omitted one, function declaration can be omitted function; Attribute name and function name expressions are supported. Note: expressions and abbreviations cannot be used at the same time.
Object’s method name property returns the method name, but be careful with a few exceptions. Object method added
- Object.is() — Used to solve partial compatibility problems with == and ===
- Object.assign() — Copy all SRC enumerable Object properties to dest Object (shallow copy)
- Object.setprototypeof (), Object.getProtoTypeof () (Object.__proto attribute)
- Object.entries(), object.keys (), Object.values()
ES6:5 ways to traverse object properties
- For-in — Enumerable attributes for itself and inheritance (except Symbol)
- Object.keys() — enumerable properties that are not themselves inherited (except Symbol)
- Object. GetOwnPropertyNames all attributes () – its key name (including an enumeration, in addition to the Symbol)
- Object. GetOwnPropertySymbols () — all attributes of the Symbol key name
- Reflect.ownkeys () — All of its own key names
The object… Operators (to be added)
(2) Symbol type
Before ES5, object attributes can only be strings, which can easily cause renaming conflicts. Symbol provides a mechanism to save attribute names that are unique. Properties of Symbol type are not returned by for-*, object.keys (), object.getpropertyNames ().
Built-in method usage of Symbol type (to be familiar with)
Data structure Set and Map
A Set is a kind of data structure similar to an array, but the difference is that its stored members are not repeated, which brings one of its applications is: deduplication. A Set is instantiated by the new keyword, and its input arguments can be objects of an array or class.
It is worth noting that only one NaN can be stored in a Set, indicating that NaN is equal to NaN in a Set data structure.
Set instance methods: add(), delete(), has(), and clear(); Traversal methods: keys(), values(), entries() and forEach(); Extended operators… The map() and filter() methods can also be used on Set structures. Therefore, it is very convenient to implement array intersection, union, difference set.
WeakSet is similar to Set,The main differences are 1. Members can only be object types; 2. Objects are weak references(If the object is no longer referenced by other objects, garbage collection mechanism will automatically reclaim the memory occupied by the object, which is unpredictable, so WeakSet cannot be traversed)
The JavaScript Object Object is a set of key-value k-V pairs, but the value of K can only be a string and Symbol. Map is also a set of K-V, but its K can be of any type. If you need a collection of key-value pairs, Map is better than Object. Map is instantiated with the new keyword.
Map instance methods: set(), get(), has(), delete(), and clear(); The traversal method is the same as Set.
Map with other data structure of mutual transformation: the Map < — – > | | Map < – > object array Map < – > JSON.
WeakMap is similar to Map, with major differences as follows: 1. Only accepts objects as key names; 2. 2. The object pointed to by the key name is not counted in the garbage collection mechanism.
Quadrilateral programming related to Proxy and Reflect
1) the Proxy
Add a layer of “interception” (” proxy “) to the target object, the external access to the object, modify must first pass this layer of interception layer. It therefore provides a mechanism to filter and override external access.
Var proxy = new proxy (p1,p2); P1 is the target object to be proxied, and P2 is the configuration object.
Proxy instances can be used as prototype objects for other objects. 13 interception methods are supported, as follows:
get set has ownKeys getOwnPropertyDescriptor defineProperty deleteProperty getPrototypeOf setPrototypeOf isExtensible preventExtensions apply construct
It is important to note that the Proxy is not transparent to the target object — even though there is no guarantee that the Proxy object will behave exactly the same as the target object without doing any interception. (The main reason is that the this inside the target object points to the proxy object when the proxy is used)
2) Reflect
Like Proxy, ES6 provides a new API for manipulating objects at the language level. At present, its object methods correspond to Proxy objects one by one. The purpose of introduction is: 1. Reflect put some internal language methods on Object (for now) 2. Modify the return values of some methods on Object objects to make them more reasonable (robust) 3. Convert the operation of an Object from imperative to functional
Asynchronous programming Promise, Generator and Async
In the JavaScript world, there are several options for asynchronous programming: 1. Callback function; 2. Events trigger listening. 3. Publish subscriber model; 4. Promise. I’ll start with Promise, and then introduce the generator function that ES6 provides, the Async function.
Promises come from the community and represent an object that represents a future outcome (Promise) of asynchronous operations. It has a total ofThree state, pending, fulfilled, rejected. Also, its stateThere are only two flip pathsThis is a pity -> depressing or pending-> once the state is reversed, it cannot be changed. It supports chained calls, error passing, and asynchronous operations written in synchronous code.
Promise is an object, and instances of this object are created as follows (resolve and reject are understood to be placeholders for future callbacks of returned Promise objects)
var p = new Promise(function(resolve,reject){// Asynchronous operationifResolve (value); //pending-> depressing, and pass the result of asynchronous operation as parameter value}else{ reject(error); // Rejected -> pending}}) p.tenn (// Rejected -> pending)function(value){// Success callback console.log("success" + value);
},function(error){// Callback console.log on failure ("error" + error);
});Copy the code
Prototype method: then() -> add a state change callback to the Promise instance; It is important to note that the then() method of the Promise object instance also returns an instance of the Promise object (a brand new instance), so the THEN () method can be invoked chained. The catch() method is an alias for then(null,reject) and is used to specify error handling callbacks when an asynchronous operation goes wrong.
Proimise object methods: all(), race(), reject(), and resolve() : All () is used to package multiple Promise instances into a new Promise instance. Only when all the state of the Promise instances is fulfilled, the new instance will become fulfilled. Otherwise, the state of the first Rejected is taken as the state of the new instance. Similarly, a new Promise instance wrapped by Race () determines its state based on the first instance that changes state first. Resolve () and reject() are used to convert existing non-Promise objects into Promise objects.
Generator functions are asynchronous programming solutions provided by ES6. A Generator function can be thought of as a state machine that encapsulates multiple internal states. It is also a traverser generator function that iterates through all the states of the state machine.
Function features: the keyword function and function name between the *, function body inside the keyword yeild.
The difference between a generator function and a normal function is that the function is called and not executed, but returns a pointer object (the traverser object). Call the next() method of the object, performing a yield logic. So the function is executed piecewise, with yield indicating a pause and next() resuming execution.
The difference between yield and return is that yield provides memory while return does not. A function can execute Yeild multiple times, but only return once
Generator functions can be assigned to the object’s symbol. iterator property to make the object traversable. Generator functions allow you to adjust the behavior of a function by injecting different values from the outside at different stages of its operation. The Generator function is an ES6 implementation of the coroutine (incomplete implementation). Generator functions can be used as containers for asynchronous tasks, where all asynchronous operations are required is indicated by Yeild. In addition, generator functions have the following features: parameter exchange inside and outside the function (the next function can input parameters and return values) and error handling (the function body can catch errors thrown outside the function). The Generator requires the Thunk function for execution and process management.
Processes, threads, and coroutines (to be added) : Coroutines are threads that cooperate and can be implemented with either a single thread or multiple threads.
Application of generator functions: 1. Synchronous expression of asynchronous operations; 2. Control flow management; 3. Deploy the Iterator interface. 4. As data structures
The async function is the syntactic sugar of the Generator function, which is improved: 1. Own actuator; 2. Return Promise;
Three comparisons: the asynchronous code using Promise has a large number of calls to its own API, and the semantics of the operation itself are mixed in, which is not very clear; The asynchronous code implemented by Generator functions is semantically clearer than Promise, but requires an executor; Async functions are written in the most concise and semantic way, and do not need an executor.
Six language level class, module support
1) class
There was an argument that JS was not object-oriented, it was object-based, that JS was based on archetypal inheritance. JS has been moving towards a different concept from other object-oriented languages since its birth. Objects are common, but classes are not. Focusing on classification vs. focusing on similarity corresponds to class-based vs. prototype-based object orientation. Starting with ES6, JavaScript provides the class keyword to define classes, although such a scheme is still based on a simulation of the prototype runtime system, most of which ES5 can implement.
The constructor’s Prototype property persists on the ES6 “class”. In fact, all methods in a class are defined on the prototype property of the class (and therefore are not enumerable).
The constructor method is the default method of the class and is automatically called when an object instance is generated using the new command. A class must have a constructor method; if it is not explicitly defined, an empty constructor method is added by default. (Default constructor); The constructor method returns the instance object (that is, this) by default; you can specify to return another object at all.
Note the difference: the class must be called with new, otherwise an error is reported. This is a major difference from normal constructors, which can be executed without new.
Inside classes and modules, the default is strict mode, so there is no need to use strict to specify the runtime mode.
A class is the prototype of an instance, and all methods defined in a class are inherited by the instance. If you prefix a method with the static keyword, it means that the method is not inherited by the instance, but is called directly from the class. This is called a “static method”.
Instance attributes can be defined at the top level of the class, in addition to above this in the constructor() method.
How are private properties and methods implemented? 2. Move the private method out of the module and use the public method call; 3. The Symbol is not perfect.
ES6 introduces a new.target attribute for the new command, which is typically used in constructors to return the constructor on which the new command is applied. If the constructor is not called with the new command or reflect.construct (), new.target returns undefined, so this property can be used to determine how the constructor is called.
2) module
Prior to ES6, there were several module loading schemes developed by the community, the most important being CommonJS and AMD. The former is used for servers and the latter for browsers. The ES6 module is designed to be as static as possible, so that the module dependencies, as well as the input and output variables, can be determined at compile time. Both CommonJS and AMD modules can only be determined at run time.
Load at compile time VS load at run time — object VS code
Module commands: export and import; A file is a module, unless imported otherwise external cannot read module properties;
Export supports variables, functions, and classes
The export command can appear anywhere in the module, as long as it is at the top of the module. If you are in block-level scope, an error is reported, as is the import command in the next section.
Input variables are read-only because they are essentially input interfaces. That is, it is not allowed to rewrite interfaces in scripts that load modules. Because import is executed statically, you cannot use expressions and variables, which are syntactic structures that are only available at run time.
When using the import command, the user needs to know the name of the variable or function to be loaded; otherwise, the command cannot be loaded. However, users will want to get started quickly and may not want to read the documentation to learn what properties and methods a module has. To make it easier for users to load the module without reading the documentation, use the export default command to specify the default output for the module.
Modules can also inherit from one another.
Seven JS object classification, and other native objects
Eight Iterator
In ES6, only Array and object can represent “collection” data structure. In ES6, Set and Map are added. Thus, the four can be combined to define new data structures. So the question is, right? How can these newly defined data structures be accessed? An Iterator is one such mechanism. It is an interface that provides a unified access mechanism for various data structures. Any data structure can be iterated by deploying the Iterator interface. The traverser object is essentially a pointer object.
A data structure is traversable as long as the Iterator interface is deployed for it. The iterator property is deployed on Symbol. Iterator interfaces are deployed on the following objects by default: Array Set Map String. 1) Deploy iterator on Symbol. Iterator; 2) Must include the next() function. The default scenario for calling the Iterator interface is: destruct assignment,… Extended operator, yeild*. The inside of the for-of loop calls the symbol. iterator method inside the data body.
For-in and for-of loops
For-in is used to iterate over object properties, the object itself and its inherited enumerable properties (not the Symbol property)
For-of loops are a uniform way to traverse all data agencies. The implementation principle is the Symbol. Iterator property deployed on the data structure.
Reference article && Related reading:
es6.ruanyifeng.com/#README
www.ruanyifeng.com/blog/2012/1…