Let and const

  • Let declares variables that are valid only in the code block in which the LET is located.
  • Let can only be declared once. Cannot duplicate declaration
  • Let has no variable promotion, and variables declared by let cannot be used before declaration

Temporary dead zone: A variable is not available until let declares it. This is grammatically called a “temporary dead zone.”

  • Const declares a read-only variable that cannot be modified after const is declared
  • Const declarations also have temporary dead zones
  • Const declares a value equal to a constant if it is a basic datatype, or a pointer that is constant if it is a complex datatype

Deconstruction assignment

Deconstructed assignment provides a way to quickly batch assign values to variables, eliminating the problem of retrieving data from nested objects

//let [a, b, c] = [1, 2, 3]; / / a = 1, b = 2, c = 3 let obj = {p: [' hello '{y:' world '}]}. let {p:[a,{y:b}]}=obj; console.log(a+' '+b)//hello worldCopy the code
  • At the heart of deconstructive assignment is one-to-one correspondence
  • Deconstructing assignments is negligible, but the location needs to be left blank

Template string

The two back quotes indicate that the content is a template string, which can be filled with variables and expressions

Function a(a,b){console.log(' hello ${a}, welcome to ${b}, now time is ${new Date().tolocaleString ()} ')} a('Tom','China')// Hello Tom, welcome to China, The time is now 4:01:56 PM on 2020/8/21Copy the code
  • All whitespace and newlines in the template string are preserved

Object literals

ES6 allows properties of objects to be written directly to variables, where the property name is the variable name and the property value is the variable value.

const age = 12;
const name = "Amy";
const person = {age, name};
person   //{age: 12, name: "Amy"}
Copy the code

Extended operator

Extended operators (…) Use to fetch all traversable properties of the parameter object and copy them to the current object.

Let a = [1, 2, 3, 4] let b =,6,7,8 [5] let c = [... a, b, 9]. The console log (c) / / [1, 2, 3, 4, 5, 6, 7, 8, 9]Copy the code

The difference between the call method and the apply method is that the call method passes parameters one by one, while the apply method passes parameters in an array. With the extension operator, the call method does not apply.

Base data type Symbol

Represents a unique property name used to define an object.

let sy = Symbol("KK"); console.log(sy); // Symbol(KK) typeof(sy); Let sy1 = symbol ("kk"); sy === sy1; // falseCopy the code

Arrow function

Basic syntax: Parameter => function body

  • Arrow functions come with a return, so you don’t get a return with curly braces

    let a=()=>5; a()//5 let b=()=>{5} b()//underfined

  • The arrow function does not have its own this; the arrow function’s this uses the execution context’s this

Iterative methods for… Of circulation

  • Cannot iterate over Object, can iterate over Array, String, Map, and Set

    const nums = ["zero", "one", "two"];
        for (let num of nums) {
          console.log(num);
        }
    const str = "zero";
        for (let item of str) {
          console.log(item);
        }
    Copy the code

The Class syntactic sugar

Class was introduced as a template for objects, and classes could be defined using the class keyword, essentially function, to make the writing of object prototypes clearer and more like the syntax of object-oriented programming.

Class a{constructor(name){constructor(name){this.name=name} Use (){console.log(' method ')}} let b=new a(' parameter ') console.log(b)Copy the code

Modular programming

ES6 introduces modularity, designed with the idea that module dependencies, as well as input and output variables, can be determined at compile time. ES6 modularity is divided into export @ and import modules.

When we want to use methods or variables of external JS files, we often need to introduce the whole external JS file into the document. If there are many such JS files, importing a document may cause repeated definition of variables and throw errors.

Modularity allows us to export {variables to be used} from external JS files instead of importing the entire JS file into the document. Then import{variable name} in the document for use.

Through modules, JS files can also be interdependent, so that the program development becomes more hierarchical, planning

  • The module will automatically turn on strict mode, whether or not you add use Strict to the module header

  • Module can import and export various types of variables, such as functions, objects, strings, numbers, booleans, classes and so on.

  • Each module has its own context, and variables declared within the module are local variables that do not pollute the global scope.

  • Each module is loaded only once (singleton). If you load the same file in the same directory again, it is directly read from memory.

The Set object

A set is a collection of data of various types. The data in a set cannot be repeated (congruent).

Methods:

  • Add, which returns a set by adding elements to the end of the set
  • Clear, remove all elements from set
  • Has, determines whether it contains
  • Delete removes the element in the set whose value is equal to the parameter

Attribute: size Query length

The Set of transformations

Var mySet = new Set(["value1", "value2", "value3"]); / / with... Var myArray = [...mySet]; Var mySet = new Set('hello'); // Set(4) {"h", "e", "l", "o"Copy the code

An array is de-duplicated using a Set object

var mySet = new Set([1, 2, 3, 4, 4]);
[...mySet]; // [1, 2, 3, 4]
Copy the code

Map object

Map objects hold key-value pairs. Any value (object or raw value) can be a key or a value.

The difference between Map objects and Object objects

  • An Object key can only be a string or a symbol, but a Map key can be any value.
  • Keys in a Map are ordered (FIFO), while keys added to objects are not.
  • The number of key-value pairs for Map can be obtained from the size property, whereas the number of key-value pairs for Object can only be calculated manually.
  • An Object has its own prototype, and the key name on the prototype chain may conflict with the key name you set on the Object.

Methods:

  • Get, query key, return value
  • Set, add key-value pairs
  • Has, queries whether there are specified elements
  • Clear, remove all key-value pairs
  • Delete: removes the specified key-value pair

Attribute: size Query length

Proxy Proxy object

The Proxy intercepts operations such as reading and function invocation of the target object, and then processes the operations. It does not operate directly on objects, but rather acts like a proxy mode, operating through objects’ proxy objects, and as it does so, additional operations can be added as needed.

  • Create a proxy object. Target represents the target object of the proxy. Handler is an object that declares the behavior of the proxy object

    let proxy = new Proxy(target, handler)

  • A proxy object intercepts 13 types of behavior (replicated) : jump addresses

1. get(target, propKey, receiver): intercepts the reading of object properties, such asproxy.fooandproxy['foo']. 2.set(target, propKey, value, receiver): Intercepts the setting of object properties, such asproxy.foo = vorproxy['foo'] = v, returns a Boolean value. 3.has(target, propKey)Intercept:propKey in proxyReturns a Boolean value. 4.deleteProperty(target, propKey)Intercept:delete proxy[propKey]Returns a Boolean value. 5.ownKeys(target)Intercept:Object.getOwnPropertyNames(proxy),Object.getOwnPropertySymbols(proxy),Object.keys(proxy),for... inLoop to return an array. This method returns the property names of all of the target object’s own properties, andObject.keys()The return result of the object contains only the traversable properties of the target object itself. 6.getOwnPropertyDescriptor(target, propKey)Intercept:Object.getOwnPropertyDescriptor(proxy, propKey)Returns the description object of the property. 7.defineProperty(target, propKey, propDesc)Intercept:Object. DefineProperty (proxy, propKey propDesc),Object.defineProperties(proxy, propDescs), returns a Boolean value. 8.preventExtensions(target)Intercept:Object.preventExtensions(proxy), returns a Boolean value. 9.getPrototypeOf(target)Intercept:Object.getPrototypeOf(proxy), returns an object. 10.isExtensible(target)Intercept:Object.isExtensible(proxy), returns a Boolean value. 11.setPrototypeOf(target, proto)Intercept:Object.setPrototypeOf(proxy, proto), returns a Boolean value. If the target object is a function, there are two additional operations that can be intercepted. 12.apply(target, object, args): Intercepts operations called by Proxy instances as functions, such asproxy(... args),proxy.call(object, ... args),proxy.apply(...). 13.construct(target, args): intercepts operations called by Proxy instances as constructors, such asnew proxy(... args).

  • Take intercepting GET as an example:

    Let obj={name:' LSQ ',age:23} let proxy=new proxy (obj,{get:function(target,key){console.log(' custom operation ') return target[key] }}) console.log(proxy.name)// Customize operation LSQ console.log(proxy.age)// Customize operation 23Copy the code
  • This brings me to the accessor property of an object:

    Var obj={_name:' LSQ ',age:23} object.defineProperty (obj,'name',{get:function(){console.log('get custom operation ') return Obj. _name}, set:function(val){console.log(' custom operation on set ') this._name=val; } }) console.log(obj.name) obj.name='qd'Copy the code
  • The difference is that the accessor properties modify the get and set properties of the original object, whereas the proxy methods do not modify the default behavior of the original object, but just wrap a layer of behavior around that behavior.

Reflect object

ES6 migrates some of Object’s methods that are clearly internal to the language to Reflect (some methods currently exist on both Object and Reflect), and future new methods will be deployed only on Reflect.

The Reflect object modifies the results returned by some methods to make them more reasonable.

The Reflect Object implements an imperative operation on Object using a function.

  • On closer inspection, the Reflect object turns out to be an object that has been transplanted from the original object into a method that belongs inside the language. The method of migration is the 13 behaviors intercepted by Proxy objects

  • The action ported out of the Reflect object is the action itself; you cannot add custom actions

    let exam = { name: "Tom", age: 24, } Reflect.get(exam, 'name'); / / "Tom" exam. The name; //"Tom"Copy the code

So what the hell is going on here? Perhaps as said above, the realization of these two content, the deep meaning I do not understand

  • The Reflect object modifies the results returned by some methods to make them more reasonable.
  • The Reflect Object implements an imperative operation on Object using a function.

Promise object (For details click)

Promise is an object that is a solution to asynchronous programming.

  • Promise creates a microtask queue, which has the advantage of being asynchronous because it has an order of execution

  • The Promise asynchronous operation has three states: Pending, fulfilled and Rejected.

    const p1 = new Promise(function(resolve,reject){ resolve('success1'); resolve('success2'); / / null});Copy the code
  • The state can only be changed in the Promise’s callback function, and once the state is changed, it cannot be changed again

  • The Promise callback takes two parameters, a success state and a failure state

  • Promises are executed immediately, as soon as they are created

Methods:

  • Then, receives two function arguments, the first callback for the successful state and the second callback for the failed state

    const p1 = new Promise(function(resolve,reject){ reject(); resolve(); / / null}). Then (() = > console. The log (' success callback), () = > console. The log (' failed callback) / / print out)Copy the code
  • The then method returns a promise object. By default, promise.resolve () is returned

    const p1 = new Promise(function(resolve,reject){ reject(); resolve(); / / null}). Then (() = > console. The log (' success callback), () = > {the console. The log (' failed callback); / / print out the return Promise. Reject ()}), then (() = > console. The log (' the success of the second layer), () = > console. The log (' the failure of the second layer)) / / print outCopy the code
  • Catch, the default failure function, has two callbacks for each THEN, which is cumbersome. The catch method is added at the end of the chain operation, giving each then method a default failure callback

    const p1 = new Promise(function(resolve,reject){ reject(); }). Then (() = > console. The log (' success callback). The catch (() = > console. The log (' the default failed callback)) / / print outCopy the code
  • .finally, an operation that executes regardless of outcome or failure, is the same as the two callbacks to then

  • Promise.all, a method that takes multiple Promise objects as arguments (in arrays) to process the Promise uniformly. This method returns a success state if multiple Promise objects are successful, and a failure state if one of them fails

    const a = new Promise((res,rej)=>res('a')); const b = new Promise((res,rej)=>res('b')); Const c = Promise. All ([a, b]), then (= > console. (a) log (a)). The catch (() = > console. The log (' failure '));Copy the code

  • Promise.allsettled, unlike All, will be executed regardless of whether an incoming Promise is settled ina success state or a failure state, just like finally and then.

    const a = new Promise((res,rej)=>res('a'));
    const b = new Promise((res,rej)=>rej('b'));
    const c = Promise.allSettled([a, b])
      .then((a)=>console.log(a))
    Copy the code

  • Promise.race, which passes the same parameters as all, but race only handles one Promise object that returns the state the fastest, which uses the state the fastest

    Const a = new Promise ((res, rej) = > setTimeout (() = > res (' success '), 0)); Const b = new Promise ((res, rej) = > setTimeout (() = > rej (' failed '), 0)); const c = Promise.race([a, b]) .then((a)=>console.log(a)) .catch((a)=>console.log(a))Copy the code

The Generator function (For details click)

By suspending the execution flow of a function with the yield keyword, it is possible to change the execution flow, thus providing a solution for asynchronous programming.

function* func(){
 console.log("one");
 yield '1';
 console.log("two");
 yield '2';
  console.log("three");
 return '3';
}
let f=func()
console.log(f.next())
 f.next()
f.next()
Copy the code
  • In my opinion, a Generator function is a function that uses the yield keyword to break up the code into separate sections and run these sections through the iterator step by step

Async function

Async is an ES7 keyword related to asynchronous operations, and is strongly associated with Promise and Generator.

  • The function that adds the async keyword before defining the function is the async function. The async function returns a Promise object by default, and the return value inside the function body is passed as an argument to the state of the Promise object

    async function a(){
            return 'a'
    }
    console.log(a())
    Copy the code

Await the expression

  • Await expression is code that exists only in async functions, blocks the execution of the program and waits for the function body following await expression to complete execution before execution

  • The await operator is used to wait for a Promise object (most of the time, of course the waiting code can be any operation, but if it is normal synchronous code there seems to be no need to use await), and it can only be used inside asynchronous async functions.

  • Returns the result of processing the Promise object. If you are waiting for something other than a Promise object, the value itself is returned.

    let a=new Promise(function(res,rej){ res() }).then(function(){ console.log('a') }) async function b(){ await A // If there is no line then the result should print b a console.log('b')} b()//a bCopy the code
  • Async /await is the syntactic sugar of the Promise object, which is essentially the Promise operation