JavaScript – ES6 summary

Var, let, const

1.1 Different scopes: block-level scopes: Declared variables are only valid within the code block scope

  • Var has no block-level scope. Let and const have block-level scope

1.2 Temporary Dead zone:

  • Only the block-level scope does not have let, const commands. Declared variables are bound within this scope and are not affected by external influences

1.3 Variable promotion: Variables are used before declaration

  • Var has a variable boost, let and const do not

1.4 Can I repeat the statement:

  • Var can be repeated and overwrites values. Let and const cannot be repeated

1.5 Whether variables are modified

  • Variables declared by var and let can be modified, but const cannot. However, if they are objects, the referenced address remains the same and the content can be modified.
  • Const must be assigned after the declaration

Is the declared value of const necessarily immutable?

Const For data of simple types (numeric, string, Boolean), the value is stored at the memory address to which the variable points and is therefore equivalent to a constant. But for complex type data (mainly objects and arrays), variable pointing to the memory address, save only a pointer to the actual data, const can guarantee the pointer is fixed (i.e., always points to the other a fixed address), as far as it is pointing to the data structure of variable, is completely unable to control. (Const values are not immutable)

Is there a variable promotion when class declares a class? Why is that?

ES6 introduces the concept of class, with the class keyword, in fact, is the expression of grammar sugar, the essence of the class is still a function object (Tencent Cloud side), but class does not exist variable promotion, declaration definition must be used before, because to facilitate class inheritance, must ensure that the subclass after the parent class definition.

Const declares an object. How can the values of its internal properties not be changed?

Freeze () is used to lock the properties of frozen objects that cannot be modified or added

2. Deconstruct the assignment

Ruan yifeng teacher’s analysis is comprehensive and vivid, strong push

Destruct assignment syntax is a JavaScript expression that takes a property/value from an object/array and assigns it to another variable. Essentially, this is “pattern matching”, as long as the pattern on both sides of the equal sign is the same, the variable on the left will be assigned the corresponding value.

2.1 Array Deconstruction

You can extract values from an array and assign values to variables in their respective locations.

2.2 Object Deconstruction

Object deconstruction differs from arrays in one important way. The elements of an array are arranged in order, and the value of a variable is determined by its position. The attributes of the object have no order. The variable must have the same name as the attribute to get the correct value. Otherwise, undefined is returned

2.3 String Deconstruction

The string is converted to an array-like object

2.4 Deconstruction of values and Boolean values

If the right hand side of the equal sign is a value and a Boolean value, it is converted to an object first. As long as the value to the right of the equals sign is not an object or array, it is first converted to an object. Undefined and NULL cannot be converted to objects, so destructuring assignments to them will result in an error.

3. Expand operators

Three points introduced in ES6 (…) As an expansion operator, to expand an array or array-like object into a series of comma-separated values. In addition, it can be used as a rest parameter residual operator.

  • Copy array:
let arr1 = [1.2.3];
let arr2 = [...arr1];
let [...arr2] = arr1/ / [1, 2, 3]
Copy the code
  • Merge array
let arr1 = [1.2.3];
let arr2 = [4.5.6];
let arr3 = [7.8.9];
[...arr1,...arr2,...arr3]/ /,2,3,4,5,6,7,8,9 [1]
Copy the code
  • Convert strings to arrays
[...'xiao']//["x","i","a","o"]
Copy the code
  • In addition to operating on arrays, it can also be used for object merging

4. Template string

Template strings are identified by backquotes (‘ ‘) and can be used as regular strings, to define multi-line strings, or to embed variables in strings.

// A common character string
`my name is xiao`
// Multi-line string
`I am xiao`
${} is used to enclose variables in a string
let name="xiao",age=18;
`My name is ${name}, i am ${age} years old`
Copy the code
  • If you want to use backquotes in template strings, you need to use backslash escape.
  • Whitespace and newlines are reserved in template strings and can be trimmed with trim()

5. Arrow function

ES6 use ()=>{} to replace the ordinary function(){}, syntax is relatively concise, daily development applications are more.

  • When arguments are empty or multiple arguments, write ()
let fn = a= > a;
// A normal function
let fn = function(a){
	return a;
}
Copy the code
  • When a function body has multiple lines of statements, it is wrapped with {} to represent the code block. There is only one line of statements and {} can be omitted when the result needs to be returned.
let fn = (a,b) = > {
	return a-b;
}
Copy the code
  • When you return an object, you need to enclose it with ()
let fn = (a,b) = > ({
	name:xiao,
	age:18
})
Copy the code

The difference between arrow functions and normal functions:

  • Different shapes: Arrow functions are defined using ()=>{}

  • Normal functions can use anonymous functions or have specific named functions, but arrow functions can only be anonymous

  • Arrow functions cannot be used for constructors; new cannot be used; Normal functions can and can create object instances

  • In normal functions, this refers to the object on which it is called and, when used as a constructor, to the object instance being created. The arrow function this points to different things: (2) The arrow function has no prototype and does not have this. This can be a global window, or this can be inherited from the first normal function in the outer layer. It has no effect on this, it can’t change the point of this

  • Arrow functions cannot bind arguments, but if this refers to a normal function, it inherits arguments from the normal function and accesses them as rest arguments or named arguments

  • Arrow functions do not hold rename function arguments, normal functions do, and the last one overwrites the previous one

  • Other differences: Arrow functions cannot be used with generator functions and the yeild keyword cannot be used; There are no prototype objects; Can’t use super

Note the interview question: What if the browser does not support the arrow function?

(1) Set the type value of the script tag to:

<script type="text/babel"><script src="browser.min.js"></script>
Copy the code

The Babel translation is divided into three stages: parsing, transforming, and generating.

  • ES6 code input
  • Babylon parses to obtain the AST
  • Plugin uses babel-traverse to traverse the AST tree and get a new AST tree
  • Generate ES5 code from the AST tree with Babel-Generator

(2) Add polyfill. Js to the header

NPM install babel-polifill --saveCopy the code

6. Rest parameters, Arguments objects

6.1 the arguments parameter

Arguments is a special local variable to functions (except for arrow functions) and is a built-in property of the function.

  • All functions come with a built-in arguments object that stores all arguments passed.
  • It’s just a pseudo-array that can be iterated over and has the length property, but it’s not really an array and can’t call its methods.
  • Can use an Array of slice method, Array. Prototype. Slice. The call (the arguments), converted to an Array.
  • Arguments’ callee attribute represents a reference to the current function and enables recursion of anonymous functions

6.2 rest parameters

ES6 introduces rest arguments, preceded by **… , such as… Args ** denotes an unknown number of arguments as an array of functions, thus solving many of arguments’ problems and allowing array methods to be used normally.

Differences between the two:

  • Rest arguments only contain arguments that have no corresponding parameters and can be part of the argument, while the Arguments object contains all arguments passed to the function and is the entirety of the argument
  • The Arguments object is a pseudo-array, and the rest argument is a real array
  • Arguments objects have additional properties, such as the Callee property
  • You need to convert arguments to arrays to use array methods
  • Both arrow functions and normal functions can use rest arguments
  • Rest parameters can be customized to accept the number of arguments, must be the last parameter of the function, the length attribute of the function does not include rest parameters

7. The set, and the map

7.1 the set

A set is a new data structure in ES6 called a set. It is similar to an array, but the member values are unique. The set itself is a constructor used to generate a set. (Array deduplicating can be done)

  • Add () adds the value and returns set
  • Delete () deletes a value and returns a Boolean value indicating whether the deletion was successful
  • Has () checks if the value exists and returns a Boolean value
  • Clear (), clears all members, returns no value

Through:

  • Keys () : Returns the key name
  • Value () : Returns the key value
  • Entries () : Returns key-value pairs
  • ForEach () : Iterates through each member using the callback function

Extension operators and Set structures combine to implement arrays or strings to implement union, intersection, and difference sets

7.2 the map

A map is a data structure called a dictionary, stored as key-value pairs, where any value (object or raw value) can be either a key or a value. Properties/methods:

  • Clear () : Clears all elements
  • Delete (key) Indicates the deleted value, which returns a Boolean value indicating whether the deletion is successful
  • Get (key) : returns the key of the specified key. If the key cannot be found, undefined is returned
  • Has (key) : Checks whether an element is included and returns a Boolean value
  • Set (key,value) : adds elements
  • ToString () : Returns a string representation
  • ValueOf () : returns the original valueOf the specified object
  • The size property returns the total number of members

Through:

  • Keys () : Returns the key name
  • Value () : Returns the key value
  • Entries () : Returns key-value pairs
  • ForEach () : Iterates through each member using the callback function

Map data structure to array, using extension operator (…)

8.promise

Promises are a new way of asynchronous programming in ES6 that addresses various issues with callbacks. Some say promises are constructors, others say they are objects, and in JavaScript everything is an object. (1) A promise has only three states:

  • Pending Asynchronous task is in progress
  • Resolved task is fulfilled successfully
  • The Rejected asynchronous task fails

(2) You must pass a parameter when creating a file, otherwise an error will be reported; (3) The arguments in the pass function are two callback functions, resolve and reject

static resolve(value){
    if (value instanceof Promise) {
      return value;
    }
    return new Promise((resolve,reject) = >{ resolve(value); })}Copy the code
static reject(value){
    return new Promise((resolve,reject) = >{ reject(value); })}Copy the code

(4) Once the state changes, it will not change again. (5) The same promise object can add multiple THEN listeners. (6) The then method returns a new Promise object after each execution. (7) The then method of the previous promise object can pass arguments to the then of the returned promise (9) If the last callback passed was a Promise object, the successful callback in the then method will be passed to the new Promise object. The success or failure of the pass to the next method is determined by the Promsie status passed. (10) Then returns a promise that catches an exception of the current THEN method. (11) Catch is the syntactic sugar of the then method

class Promise{
	//....
    catch(onRejected){
    	 return this.then(null,onRejected)
    }
}

Copy the code

8.1 promise. All

Summarize the results of multiple promises, and make asynchronous requests in parallel:

  • Return success in the requested order when all results are returned successfully
  • When one of them fails, enter the fail method
static all(promiseArr){
	// Return the new Promise instance
    return new Promise((resolve,reject) = >{
      var length = promiseArr.length
      var result = [];
      for(var i = 0; i<length; i++){let _promise = promiseArr[i];
        function handlerResolve(index,item){
          result[index] = item;
          // Since the promise will be completed at different times, use --length to determine whether it is appropriate to complete all processing
          --length;
          if(length == 0){ resolve(result); }}Promise.resolve(_promise).then((value) = >{
          handlerResolve(i,value);
        },reason= >{
          // Return on failure
          reject(reason)
          return; })}})}Copy the code

Application Scenarios:

1. Multiple request results are combined: a page has multiple requests, we need to render all the requests together after returning data; 2. Merge request results and handle errors. 3. Verify whether the results of multiple requests meet the following conditions: form verification, multiple fields, can be submitted only after all the verification passes

8.2 promise. Race

The race function returns a promise that will be completed in the same way as the first promise passed. It can be resolved or failed, depending on which of the two is the first.

Application Scenarios:

1. The image request timed out. 2. Request timeout prompt: the last second to brush the news, the next second to enter the elevator, the prompt network is not good;

static race(promiseArr){
    return new Promise((resolve,reject) = >{
      var length = promiseArr.length
      for(var i = 0; i<length; i++){let _promise = promiseArr[i];
        // Return the result first
        Promise.resolve(_promise).then(value= >{
          resolve(value)
          return;
        },reason= >{
          reject(reason)
          return; })}})}Copy the code

8.3 promise. Prototype. Then

The chain call to promise

Application Scenarios:

1. The next request depends on the result of the previous request. 2. Use of middleware functions: the number of return interfaces is large, so processing in one THEN is bloated, and multiple rendering data are sent to THEN respectively.

8.4 promise. AllSettled

The promise.allSettled () method takes a set of Promise instances as parameters and wraps them into a new Promise instance. The wrapper instance will not complete until all of these parameter instances return the result, whether this is fulfilled or Rejected. This method was introduced by ES2020. This method returns a new Promise instance. Once it is fulfilled, the state is always fulfilled and will not become Rejected. After the state becomes depressing, the Promise listener receives an array of parameters, each member corresponding to an incoming promise.allSettled () Promise instance.

static MyallSettled(promises){
   let resArr=new Array(promises.length);
   let num=0;
   retrun new Promise(resolve= >{
       promises.forEach((item,key) = >{
           let obj={};
           item.then(v= >{
               obj['status'] ="fulfilled";
               obj.value=v;
               resArr[key]=obj;
               num++;
               if(num===promises.length){ resolve(resArr); }},r= >{
               obj['status'] ="rejected";
               obj.reason=r;
               resArr[key]=obj;
               num++;
               if(num===promises.length){ resolve(resArr); }})})}); }Copy the code

Application Scenarios:

  • Not dependent on each other, one is rejected and has no effect on the others
  • Expect to know the result of each promise execution

9. Iteration and generation

9.1 Iterator Iterator

Iterators are a special type of object. All iterators have a next() method that returns a result object each time it is called. The result object has two attributes: value, which represents the next value to be returned; The other is done, which is a Boolean value that returns true if there is no more data to return. The iterator also holds an internal pointer to the location of the value in the current collection, and each time the next() method is called, the next available value is returned

If the next() method is called after the last value is returned, the value of done in the returned object will be true, and the value will contain the final value returned by the iterator. This return value is not part of the data set. It is similar to the return value of a function, and is the last method to pass information to the caller during the function call. Return undefined if there is no relevant data

9.2 Generator Generator

Generator functions, which can suspend the execution flow of a function using the yield keyword, provide the possibility to change the execution flow, thus providing a solution for asynchronous programming.

Generator has two distinct parts from ordinary functions. One is to add * between function and function name. There’s a yield expression inside the function. Where * indicates that the function is a Generator, and yield defines the state inside the function.

In general, the yield expression returns undefined if the next method takes no arguments, and when the next method takes arguments, the argument returns the yield of the previous step. The yield* expression indicates that yield returns an traverser object to be used to call another Generator function within a Generator function.

10. Async and await

10.1 async

Async is an ES7 keyword related to asynchronous operations, and is strongly associated with Promise and Generator. The async function returns a Promise object, and callbacks can be added using the then method. Async declaration mode:

  • Function declaration:async function fn(){}
  • Expression declaration:let fn = async function(){}
  • Object declaration:
let obj = {
	async fn(){}}Copy the code
  • Arrow function declaration:let fn = async() => {}

10.2 await

The await operator is used to wait for a Promise object and can only be used inside the async function. Returns the result of processing the Promise object. If you are waiting for something other than a Promise object, the value itself is returned. If a Promise is passed to an await operator, await will wait for the normal processing of the Promise to complete and return the result of its processing.

11.class

ES6 introduces class, which uses prototype objects to imitate object-oriented classes and inheritance. Creating objects through class classes can avoid repetitive code and meet the characteristics of object-oriented. If two or more objects have similar structures, a template can be abstracted and similar objects copied from the template. (Essentially inheritance)

But there is no real class primitive type in JS. Classes are just syntactic sugar applied to prototype objects.

The function declaration has variable promotion, but the class declaration does not

11.1 the constructor

Constructor is a special method used to create and initialize an object. There can only be one special method named constructor in a class, and an error will be reported if there are more than one.

The constructor method of the parent class can be called from constructor via the super keyword.

11.2 inheritance

ES6 provides an extended class subclass of extends implementation class extends parent

class Parent{
    constructor(name,age){
        this.name=name;
        this.age=age; }}class Son extends Parent{
    constructor(name,age,score){
        super(name,age)
        this.score=score; }}Copy the code
  • Subclasses must call the super method in the constructor method
  • You can only use this after calling super

That is, you can take the attributes and methods of the parent class before you can continue adding your own attributes and methods

12.symbol

ES6 Added a data type

  • Instance is unique and immutable, a unique identifier that can be used as a unique attribute name for an object
  • Concealment, when used as object property key, for… In does not traverse the key of symbol

Symbol is like a constructor that creates a Symbol object, and the symbol takes a parameter that represents a description of the value of the generated symbol

let name = Symbol("name")
Copy the code

Continue to add….. later