当前位置:网站首页>ES6

ES6

2022-04-23 17:49:00 Front end more

ES6

1.var、let 、const The difference between ,var Variable promotion and function promotion

  • var Declaration variable has variable promotion ,let and const non-existent
  • var Will be with window Phase mapping ( Will hang a property ), and let Not with window Phase mapping
  • var The scope of the function is the scope of the function , and let、const The scope of is block level scope
  • Under the same scope let and const Variables cannot be declared repeatedly , and var Sure
  • In the same scope let and const There will be a temporary dead zone before declaration , That is to say let、const Before the statement , Variables cannot be used
  • const
    • Once declared must be assigned , Out of commission null placeholder
    • Cannot be modified after declaration
    • If compound type data is declared , Its properties can be modified

stay js The engine precompiles before the code is executed , Variable and function declarations are promoted to the top of their corresponding scopes during precompiling

Variable Promotion : The declaration of the variable will be promoted to the top of the current scope , The assignment of variables does not increase

Function enhancement : The declaration of the function will be promoted to the top of the current scope , But it doesn't call the function , Function promotion takes precedence over variable promotion .

2.Promise( What is? Promise?)

Promise :ES6 The introduction of a new solution to asynchronous programming , Grammar is a Constructors , Used to encapsulate asynchronous operations and obtain the results of their success or failure . Promise Objects have three states : initialization pending success fulfilled Failure rejected

  • Promise It's an object , Used to represent and pass the final result of asynchronous operation
  • Promise {: PromiseResult} PromiseState: state PromiseResult: Return value
  • Promise The main way of interaction : Pass the callback function into then Method to get the final result or the cause of the error
  • Promise Performance in code writing : With “ call chaining ” Instead of the callback function, it is nested layer by layer ( Back to hell )p.then().then()

When we're building Promise When , The code inside the constructor is Execute now Of .Promise The constructor is the main thread , and Promise.then It's a micro task .

new Promise((resolve, reject) => {
    
  console.log('new Promise');
  resolve('success');
});
console.log('finifsh');

//  Print first new Promise,  Re print  finifsh

call Promise Object's then Method , The two parameters are functions , The return is promise object , The object state is determined by the execution result of the callback function .

	// establish Promis object 
	const p = new Promise((resolve, reject) => {
    
        setTimeout(() => {
    
          resolve(" success ");
        }, 1000);
      });
  
      //1. If the return result in the callback function is   Not promise object , Status is success , The return value is the object success value fulfilled
      const result = p.then(
        (value) => {
    
          console.log(value); // success 
          return 1;
        },
        (reason) => {
    }
      );
      console.log(result); //Promise {<fulfilled>: 1}
-------------------------------------------------------------------------------------------
      //2. If the return result in the callback function is promise object , this promise The object determines the above promise object p The state of 
      const result = p.then(
        (value) => {
    
          console.log(value); // success 
          return new Promise((resolve, reject) => {
    
            resolve("ok"); 
            reject("err"); 
          });
        },
        (reason) => {
    }
      );
      console.log(result);// //Promise {<fulfilled>: 'ok} Promise {<rejected>: 'err'} 
-------------------------------------------------------------------------------------------
      //3. Throw an error 
      const result = p.then(
        (value) => {
    
          console.log(value); // success 
          throw " Error "; 
        },
        (reason) => {
    }
      );
      console.log(result); // Promise {<rejected>: ' Error '} 

​ Promise Realized call chaining , That is to say, every call then After that, all the people who returned were Promise, And it's a brand new Promise, The reason is that the state is immutable . If you are in the then in Used return, that return The value of will be Promise.resolve() packing .

Promise.resolve(1)
  .then((res) => {
    
    console.log(res); // => 1
    return 2; //  Package as  Promise.resolve(2)
  })
  .then((res) => {
    
    console.log(res); // => 2
  });

Promise It's also a good solution Back to hell The problem of .

Back to hell : An asynchronous request is nested with an asynchronous request , An asynchronous request depends on the execution result of another , Use callbacks to nest with each other , Low code readability 、 Hard to write 、 Inconvenient for later maintenance

ajax(url)
  .then((res) => {
    
    console.log(res);
    return ajax(url1);
  })
  .then((res) => {
    
    console.log(res);
    return ajax(url2);
  })
  .then((res) => console.log(res));

3.async and await

async and await The combination of the two syntax can make asynchronous code look like synchronous code , Simplify the writing of asynchronous functions

async function :

1.async The return value of the function is promise object ;

2.promise The result of the object is determined by async The return value of the function execution determines

3.async yes Generator Grammatical sugar of function , Also on Generator The function is improved , It's right yield Simple encapsulation

    async function fn() {
    
      //1. If the return result is   Not promise object , Status is success , The return value is the object success value fulfilled
      return 123;
      //2. Throw an error 
      throw " Error ";
    }
    const result = fn();
    console.log(result); // Promise {<fulfilled>: 123} Promise {<rejected>: ' Error '}
-----------------------------------------------------------------------------------------
    async function fn() {
    
      //3. If returned promise object , Then the final result is Promise object 
      return new Promise((reslove, reject) => {
    
        //resolve(' success ');
        reject(' Failure ');
      })
    }
    const result = fn();
    console.log(result); //Promise {<rejected>: ' Failure '}
    // then Method to get the final result or the cause of the error 
    result.then(
      (value) => {
    
        console.log(value);
      },
      (reason) => {
    
        console.log(reason); // Failure 
      }
    )

await expression :

1.await Must be written in aysnc Function ;

2.await The following expression is generally Promise object ;

3.await The return is Promise The value of success ;

4.await Of Promise failed , Will throw an exception , Unable to deal with promise Back to reject object , Need to pass through try…catch Capture processing .

    //async function  + await expression : An asynchronous function 
    async function fn() {
    
      //await  Back to promise Success value 
      let result = await new Promise((resolve, reject) => {
    
      resolve(' success ')
    });
      console.log(result); // success 
    }
    fn();

One await Example :

let a = 0;
let b = async () => {
    
  a = a + (await 10);
  console.log('2', a);
};
b();
a++;
console.log('1', a);

// First, the output  ‘1’, 1
// At output  ‘2’, 10
  • First of all, the function b Execute first , In carrying out the await 10 Previous variable a still 0, because await Internally implemented generator ,generator Will keep things in the stack , So at this point a = 0 Preserved
  • because await Is asynchronous operation , Later expressions do not return Promise Words , Will be packaged as Promise.reslove( Return value ), Then it will execute the synchronization code outside the function
  • Synchronization code a++ And printing a After execution, start executing asynchronous code , Use the saved value , Now a = 0 + 10

The above explanation refers to await Internally implemented generator, Actually await Namely generator add Promise The grammar sugar of , And the internal implementation of automatic execution generator.

4. Arrow function , And the difference from ordinary functions , Arrow functions can be used as constructors new Do you ? The function of the arrow function

Arrow function ()=>{}:

  1. If there is only one parameter , Then brackets can be omitted ;
  2. If there is only one statement in the function body , The curly braces can be omitted , The return value of the function is the execution result of the statement ;

The difference from ordinary functions

  1. Ordinary functions have function promotion , The arrow function does not
  2. Arrow functions don't have their own this,arguments, Arrowhead function this Point to parent : First, find... From its parent scope , If the parent scope is still an arrow function , Look up again , Until I find this The direction of .
  3. Arrow function cannot be a constructor , in other words , Not available new command ( No, this), Otherwise, an error will be thrown .
  4. No, yield attribute , Cannot be used as a generator Generator function

Arrow function cannot new

  • There is no one's own this, Cannot call call and apply
  • No, prototype,new Keyword internal need to put the new object's _proto_ Pointing to a function prototype

The function of the arrow function :

1. Grammatical simplicity

2. Can implicitly return

// Show return 
const double3 = numbers.map(number => {
    
    return number * 2;  
})
// Implicit return 
// Get rid of return And curly braces , Move the returned content to one line , More concise ;
const double3 = numbers.map(number => number * 2);

3. No binding this

this Is actually inherited from its parent scope this, Of the arrow function itself this It doesn't exist , This is equivalent to the arrow function this It was determined at the time of the statement ,this The direction of does not change with the call of the method

6. The advantages and disadvantages of asynchronous implementation methods and their respective methods

Mode one : Callback function (callback): Pass a function as an argument to another function , When that function is executed , Then execute the function passed in , This process is called callback

Back to hell : Callback functions are nested layer by layer , Low code readability 、 Inconvenient for later maintenance

advantage : Solved the problem of synchronization ( As long as one task takes a long time , The next task has to wait in line , Will delay the execution of the whole procedure .)

shortcoming : Back to hell , Only one callback function can be specified per task , You can't return.

Mode two : Promise

Promise Just to solve it callback The problem of .

Promise Implementation of the chain call , That is to say, every time then All of them are brand new Promise, If we were then in return ,return The result will be Promise.resolve() packing

advantage : Solved the problem of callback to hell

shortcoming : Can't cancel Promise , The error thrown internally needs to be caught through the callback function

Mode three : generator Gnenrator

Generator Is a solution to asynchronous programming , Solve callback hell

You're right Gnenrator The understanding of the ?

Generator Function is a state machine , Encapsulates multiple internal states . perform Generator The function returns an iterator ( iterator ) object , You can traverse through Generator Every state inside a function , But only call next Method to traverse the next internal state , So it actually provides a function that can pause execution .yield An expression is a pause flag .

Must call the next Method , Move the pointer to the next state . in other words , Every time you call next Method , The internal pointer is executed from the function header or the last stop , Until we meet the next one yield expression ( or return sentence , without return sentence , To the end of the function ) until .yield Expressions are flags that pause execution , and next Method can resume execution

Mode 4 :async/await

advantage : Clear code , Don't look like Promise Write a lot of then chain , Dealt with the problem of callback to hell

shortcoming :await Transform asynchronous code into synchronous code , If multiple asynchronous operations are used without dependency await Will lead to performance degradation .

7. The way to solve the hell of asynchronous callback

Promise、generator、asynac/await

8.forEach、for in、for of The difference between

forEach Traversal array , But you can't use break、continue and return sentence

for...in Is used to loop with a string key The object of the method . It's actually a loop ”enumerable“( enumerable ) Designed for objects

for...of Array objects can be traversed , Traversing an object requires passing and Object.keys()

for in What circulates is key,for of What circulates is value

Enumerable properties It refers to those internal “ enumerable ” Flag set to true Properties of .

For properties initialized by direct assignment and properties , The default value of this indicator is true.

Js The prototype properties of the basic data type cannot be enumerated , adopt Object.defineProperty0 Method specification enumeralbe by false The properties of cannot be enumerated .

9.Set、Map The difference between

Set aggregate : It's like an array , But the values of members are unique . Array weight removal

Map aggregate : Similar to the object , It's also a set of key value pairs , but ’ key ’ Not limited to strings , Various types of values ( Including objects ) It can also be used as a key .

Application scenarios Set For data reorganization ,Map For data storage

Set
1, Members cannot be duplicated
2, Only the key value has no key name , It's like an array
3, Traversable , There are methods add, delete,has

Map:
1, It is essentially a set of key value pairs , Like a collection
2, Traversable , It can be converted with various data formats

10.filter、map、reudce Higher order function

filter Filter ,filter() Test all elements with the specified function , And create a new array containing all the elements that passed the test .filter The callback function in must return a boolean value , When to return to true when , The function will automatically call back this time n Add to a new array , by false when , Will filter this n.

map mapping ,map() Method Returns a new array , The elements in the array are the post value processed by the calling function of the original array elements .

reduce() Method Receive a function as accumulator , Every value in the array ( From left to right ) Start to shrink , The final calculation is a value .

11. What is? Proxy?

Proxy Can be interpreted as , Set up a layer in front of the target object “ Intercept ”, External access to the object , All must be intercepted through this layer first , So it provides a mechanism , It can filter and rewrite external access .Proxy The original meaning of this word is agent , It's used here to show that it comes from “ agent ” Some operations , It can be translated into “ Agent ”.

12. modularization

modularization It means that a large program file , Split into many small files , Then combine the small files .

A module is a set of methods to implement a specific function

advantage :1. Prevent naming conflicts ;2. Code reuse ;3. High maintenance ;

Realize modularization

  • AMD
  • CMD
  • CommonJS modular
  • ES6 modular

13. Module loading scheme comparison :CommonJS modular And ES6 modular

CommonJS modular , It passes through require To introduce modules , adopt module.exports Define the output interface of the module . This module loading scheme is a server-side solution , It introduces modules in a synchronous way , Because on the server side, the files are stored on the local disk , So reading is very fast , So there's no problem loading synchronously . But if it's on the browser side , Because the module is loaded using network requests , So it's more appropriate to use asynchronous loading .

ES6 modular Use import and export To import and export modules in the form of .

difference :

  • **CommonJS The output of the module is a copy of the value ,ES6 The module outputs a reference to a value .**CommonJS The output of the module is a copy of the value , Changes within the module do not affect this value .ES6 Modules are dynamic references , And it doesn't cache values , The variables in a module are bound to the module they are in .

  • **CommonJS Modules are run time loaded ,ES6 Module is a compile time output interface .**CommonJS Modules are objects , That is to load the whole module before input , Generate an object , Then read the method from the object , This load is called “ Load at run time ”. and ES6 Module is not an object , Its external interface is just a static definition , It will be generated during the static parsing phase of the code .

14. Deconstruct assignment

An array of deconstruction

let [a, b, c] = [1, 2, 3]   //a=1, b=2, c=3
let [d, [e], f] = [1, [2], 3]    // Nested array deconstruction  d=1, e=2, f=3
let [g, ...h] = [1, 2, 3]   // Array splitting  g=1, h=[2, 3]
let [i,,j] = [1, 2, 3]   // Discontinuous deconstruction  i=1, j=3
let [k,l] = [1, 2, 3]   // Incomplete deconstruction  k=1, l=2

Object to deconstruct

let {
    a, b} = {
    a: 'aaaa', b: 'bbbb'}      //a='aaaa' b='bbbb'
let obj = {
    d: 'aaaa', e: {
    f: 'bbbb'}}
let {
    d, e:{
    f}} = obj    // Nested deconstruction  d='aaaa' f='bbbb'
let g;
(g = {
    g: 'aaaa'})   // Deconstruct... With declared variables  g='aaaa'
let [h, i, j, k] = 'nice'    // String deconstruction  h='n' i='i' j='c' k='e'

版权声明
本文为[Front end more]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230550117842.html