ECMAScript 6 (ES6) is the next generation standard for the JavaScript language. Because the current version of ES6 was released in 2015, it is also called ECMAScript 2015. In other words, ES6 is ES2015. While not all browsers are currently compatible with all ES6 features, more and more programmers are using ES6 in real projects. Today I’ll summarize the common es6 attribute methods at work

1.let

ES6 has added the let command for health variables. Its use is similar to var, but the declared variable is only valid within the code block in which the let command resides.

for(let i = 0; i < 10; i++) {

 }
 console.log(i) //ReferenceError: i is not defined



for(var i=0; i<10; i++){



}

console.log(i) //10

`
Copy the code

In the code above, the counter I is only valid inside the for loop, and references outside the loop report an error. Let has block-level scope. Var does not have block-level scope problems, there are problems with global variable hints,

2.const

Const declares a read-only constant. Once declared, its value cannot be changed.

Const a = 10; A = 20. console.log(a) //TypeError: Assignment to constant variable. The above code shows that changing the value of a constant causes an error.Copy the code

A variable declared by const may not change its value, which means that a const, once declared, must be initialized immediately and cannot be left for later assignment.

const a;
    console.log(a)
Copy the code

The code above shows that const is declared without assignment, and an error is reported.

Let the const

1. Do not repeat the statement

2. Both have block-level scope problems

3. Only valid within the block-level scope of the declaration.

 

3. Template string

A template string is a new representation of a string

(1) Basic usage

  

let s1 = ` hello `
let s2 = ' hello '
Copy the code

(2) String and variable splicing

 

let s3 =" a " + s1 + " b " + s2;
let s4 = ` a ${s1} b ${s2}`;  
Copy the code

 

(3) String newline

var box =`<div>
            <p>
              <span>123</span>
            </p>
            <p>${a1}</p>
         </div>`;
Copy the code

The appearance of template string, greatly changed the traditional string concatenation method, reduce the probability of code error. Improve development efficiency

4. Deconstruct assignments

ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern known as deconstruction

4.1: Object structure assignment

var obj ={ name:"abc",age:18 };
    //用解构赋值的方式获取name、age

    let { name } = obj; //创建了一个变量name,值=obj.name
    console.log(name);  //"abc"

    let { age } =obj;
    console.log(age);  //18
Copy the code

4.1: Function parameter structure assignment

function f1(obj){ console.log(obj.age); Console. log(obj.height)} function f1({age,height}){console.log(age); console.log(height) } f1({age:5,height:180})Copy the code

5. The rest parameters

ES6 introduces the REST parameter (of the form… Variable name), used to get extra arguments to a function so you don’t need to use the arguments object. The rest argument goes with a variable that puts the extra arguments into an array.

Console.log (arguments.length); function fn(){console.log(arguments.length); for(var i =0 ; i<arguments.length; i++){ console.log(arguments[i]); }} fn(1,3,5) //3 // fn("a","b","c","d","e") //5Copy the code

You can’t use arguments inside es6 arrow functions. To remedy this problem, rest arguments should be created instead

 

/ /... //--> generates a variable that is an array containing all the arguments passed when this function is called. Function q(... Args){// Verify that args is an array. console.log(args instanceof Array); //true console.log(Object.prototype.toString.call(args)); //"[object Array]" console.log(Array.isArray(args)); //true the new method console.log(args) in ES5; } q,3,5 (1); Q (2,3,4,5,6,7,8);Copy the code

 

Arrow function

ES6 allows functions to be defined using arrows (=>).

 

Scenario: Used to replace anonymous functions

// Anonymous function div.onclick=function(){console.log(" hello ")} // arrow function div.onclick=()=>{console.log(" hello ")}Copy the code

Arrow function with one argument

var fn=(a)=>{ console.log("abc"); } // equivalent to: var fn=a=>{console.log(" ABC "); }Copy the code

Arrow function with 2 or more arguments

 var f=(a,b,c)=>{
        console.log("abc")
    }
Copy the code
Var p={age:18, run ()=>{setTimeout(()=>{//this:window console.log(this); // This is window},100)}, travel:function(){//this:p setTimeout(()=>{console.log(this); * * * : es6: say(){console.log("say this: ",this); SetTimeout (()=>{console.log("say internal delay function: ",this); //this is p},100)},} p.run(); p.travel(); p.say();Copy the code

How are arrow functions different from normal anonymous functions?

1. The this object inside the function is the object of the definition, not the object of the use

2. Do not use it as a constructor, that is, do not use the new command, otherwise an error will be thrown

You can’t use arguments objects. This object does not exist in the function body. If you do, use the REST argument instead.

4. Arrow functions cannot be used as Generator functions because yield cannot be used.

5. Generator functions are now often replaced with async

 

7. Object extension

The spread operator (spread) is three points (…) . Use to fetch all traversable properties of the parameter object and copy them into the current object \

7.1Object.assign: Copy inheritance is implemented

  

/ / Object. The assign is the Object of shallow copy var source = {age: 18, height: 170, the className: "class 2 grade 3}"/var/clone a new Object newObj=Object.assign({},source); console.log(newObj); var newObj2={}; Object.assign(newObj2,source); console.log(newObj2);Copy the code

The above can implement shallow copy, but the code is a bit too much, ES6 object extension, a cool way to solve the problem of shallow copy,

Var car={brand:"BMW",price:"368000",length:"3 "} var car={brand:"BMW",price:"368000",length:"3 "} car } console.log(car2); Var car3={... var car3={... Car,length:"4 "} console.log(car3); var car4={ ... car,type:"SUV"} console.log(car4); var car5={... car4,price:"69800",brand:"BYD"}; console.log(car5);Copy the code

Object extension, simple and convenient, more brief code, less code to achieve more powerful functions.

 

8.Promise

Promise is a solution for asynchronous programming (callback hell)

In the old days promises were written like this, layer by layer,  $.get("/getUser",function(res){ $.get("/getUserDetail",function(){ $.get("/getCart",function(){ $.get("/getBooks",function(){ //... })})})})Copy the code

Basic use of promise

Var promise=new promise ((resolve,reject)=>{$.get("/getUser",res=>{$.get("/getUser",res=>{$.get("/getUser",res=>{$.get("/getUser",res=>{ //c resolve(res) // })}) //a, promise.then(res=>{//d, console.log(res); })Copy the code

Promise implements multiple layers of callbacks

New Promise((resolve,reject)=>{$.get("/getUser",res=>{resolve(res)})}). Then (res=>{// user basic information return new Resolve (resolve=>{$. Get ("/getUserDetail",res=>{resolve(res)})}). Then (res=>{resolve(res)}). $.get ("/getCart ", res = > {resolve (res)})})}). Then (res = > {} / / shopping cart information)Copy the code

Promise implements error handling

new Promise((resolve,reject)=>{ $.ajax({ url:"/getUser", type:"GET", success:res=>{ resolve(res); }, error: res = > {reject (res)}})}). Then (resSuccess = > {/ / successful return value}, resError = > {/ / the return value of failure})Copy the code