当前位置:网站首页>ES6, ES7, es8 Learning Guide

ES6, ES7, es8 Learning Guide

2020-11-09 22:19:11 Front end development blog

author :CrazyCodeBoy
link :https://www.jianshu.com/p/1ae...

summary

ES Full name ECMAScript,ECMAScript yes ECMA Developed a standardized scripting language . at present JavaScript The use of ECMAScript Version is ECMAScript-262.

ECMAScript Standards are based on some old technology , The most famous is JavaScript ( netscape ) and JScript ( Microsoft ). It was originally created by Netscape Brendan Eich The invention , It first appeared in Netscape Navigator 2.0 The browser .Netscape 2.0 And Microsoft Internet Explorer 3.0 It appears on all browsers in the following order .

image.png

Understand these features , Not only can make our coding more in line with the specification , And it can improve us Coding The efficiency of .

ES6 Characteristics of

ES6 There are many characteristics , stay ES5 Release near 6 year (2009-11 to 2015-6) Only then can it be standardized . The time span between two releases is large , therefore ES6 There are many features in .

Here are a few common :

  • class
  • modularization
  • Arrow function
  • Function parameter defaults
  • Template string
  • Deconstruct assignment
  • Extension operator
  • Object attribute shorthand
  • Promise
  • Let And Const

1. class (class)

Be familiar with Java,object-c,c# For developers of pure object-oriented languages , Will be right. class There is a special feeling .ES6 Introduced class( class ), Give Way JavaScript Object-oriented programming becomes simpler and easier to understand .

 class Animal {
    //  Constructors , It will be called when instantiated , If you don't specify , Then there will be a default constructor without parameters .
    constructor(name,color) {
      this.name = name;
      this.color = color;
    }
    // toString  It's a property on a prototype object 
    toString() {
      console.log('name:' + this.name + ',color:' + this.color);

    }
  }

 var animal = new Animal('dog','white');// Instantiation Animal
 animal.toString();

 console.log(animal.hasOwnProperty('name')); //true
 console.log(animal.hasOwnProperty('toString')); // false
 console.log(animal.__proto__.hasOwnProperty('toString')); // true

 class Cat extends Animal {
  constructor(action) {
    //  Subclasses must be in constructor It is specified in super  function , Otherwise, an error will be reported when creating an instance .
    //  If it doesn't top consructor, Default band super Functional constructor Will be added 、
    super('cat','white');
    this.action = action;
  }
  toString() {
    console.log(super.toString());
  }
 }

 var cat = new Cat('catch')
 cat.toString();

 //  example cat  yes  Cat  and  Animal  Example , and Es5 Exactly the same .
 console.log(cat instanceof Cat); // true
 console.log(cat instanceof Animal); // true 

2. modularization (Module)

ES5 Native modularity is not supported , stay ES6 As an important component, the module in is added . The function of the module mainly consists of export and import form . Each module has its own scope , The mutual calling relationship between modules is through export To specify the exposed interface of the module , adopt import To reference the interface provided by other modules . It also creates namespaces for modules , Prevent function naming conflicts .

export (export)

ES6 Allow to use... In a module export To export multiple variables or functions .

Export variables

//test.js
export var name = 'Rainbow' 
Experience :ES6 It not only supports the export of variables , It also supports constant export . export const sqrt = Math.sqrt;// Derived constants

ES6 Treat a file as a module , The above module passes export Output a variable out . A module can output multiple variables at the same time .

 //test.js
 var name = 'Rainbow';
 var age = '24';
 export {name, age}; 

The export function

// myModule.js
export function myModule(someArg) {
  return someArg;
} 

Import (import)

After defining the output of the module, it can pass through another module import quote .

import {myModule} from 'myModule';// main.js
import {name,age} from 'test';// test.js 
Experience : One import Statement can import the default function and other variables at the same time . import defaultMethod, { otherMethod } from 'xxx.js';

3. arrow (Arrow) function

This is a ES6 One of the most exciting features of .=> Not just keywords function Abbreviation , It also brings other benefits . The arrow function shares the same code that surrounds it this, Can help you solve it well this Direction problem of . experienced JavaScript Developers are familiar with things like var self = this; or var that = this This kind of quotation peripheral this The pattern of . But with the help of =>, There's no need for this model .

The structure of the arrow function

Arrow function arrow => It was an empty bracket 、 A single parameter name 、 Or multiple parameter names in parentheses , And the arrow can be followed by an expression ( As the return value of the function ), Or the function body enclosed in curly brackets ( It needs to pass by itself return Return value , Otherwise, it returns zero undefined).

//  An example of an arrow function 
()=>1
v=>v+1
(a,b)=>a+b
()=>{
    alert("foo");
}
e=>{
    if (e == 0){
        return 0;
    }
    return 1000/e;
} 
Experience : Whether it's an arrow function or bind, Each time it is executed, a new function reference is returned , So if you need a function reference to do something else ( For example, uninstalling the listener ), Then you have to save the reference yourself .

Traps when uninstalling listeners

Wrong way
class PauseMenu extends React.Component{
    componentWillMount(){
        AppStateIOS.addEventListener('change', this.onAppPaused.bind(this));
    }
    componentWillUnmount(){
        AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this));
    }
    onAppPaused(event){
    }
} 
The right way
class PauseMenu extends React.Component{
    constructor(props){
        super(props);
        this._onAppPaused = this.onAppPaused.bind(this);
    }
    componentWillMount(){
        AppStateIOS.addEventListener('change', this._onAppPaused);
    }
    componentWillUnmount(){
        AppStateIOS.removeEventListener('change', this._onAppPaused);
    }
    onAppPaused(event){
    }
} 

In addition to the above , We can still do this :

class PauseMenu extends React.Component{
    componentWillMount(){
        AppStateIOS.addEventListener('change', this.onAppPaused);
    }
    componentWillUnmount(){
        AppStateIOS.removeEventListener('change', this.onAppPaused);
    }
    onAppPaused = (event) => {
        // Take a function directly as a arrow function To define , It's bound when it's initialized this The pointer 
    }
} 
It should be noted that : Whether it's bind Or arrow function , Each time it is executed, a new function reference is returned , So if you need a function reference to do something else ( For example, uninstalling the listener ), Then you have to save the reference yourself .

4. Function parameter defaults

ES6 It supports setting default values for functions when they are defined :

function foo(height = 50, color = 'red')
{
    // ...
} 
Don't use default values :
function foo(height, color)
{
    var height = height || 50;
    var color = color || 'red';
    //...
} 

It's OK to write like this , But when The Boolean value of the parameter is false when , There will be problems . such as , We call it this way foo function :

foo(0, "") 

because 0 The Boolean value of is false, such height The value of will be 50. Empathy color The values for ‘red’.

So , Function parameter defaults It can not only make the code more concise but also avoid some problems .

5. Template string

ES6 Support Template string , Make string splicing more concise 、 intuitive .

Don't use Template Strings :
var name = 'Your name is ' + first + ' ' + last + '.' 
Use the template string :
var name = `Your name is ${first} ${last}.` 

stay ES6 Pass through ${} You can complete string splicing , Just put the variables in braces .

6. Deconstruct assignment

The deconstruction assignment syntax is JavaScript An expression of , It is convenient to quickly extract values from arrays or objects and assign them to defined variables .

Get the values in the array

Get a value from an array and assign it to a variable , The order of the variables corresponds to the order of the objects in the array .

var foo = ["one", "two", "three", "four"];

var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"

// If you want to ignore certain values , You can get the value you want as follows 
var [first, , , last] = foo;
console.log(first); // "one"
console.log(last); // "four"

// You can write like this 
var a, b; // Declare variables first 

[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2 

If you don't get a value from an array , You can set a default value for the variable .

var a, b;

[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7 

The value of two variables can be easily exchanged by deconstructing the assignment .

var a = 1;
var b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1 

Get the value in the object

const student = {
  name:'Ming',
  age:'18',
  city:'Shanghai'  
};

const {name,age,city} = student;
console.log(name); // "Ming"
console.log(age); // "18"
console.log(city); // "Shanghai" 

7. Extension operator (Spread operator)

Extension operator ... Can be called in function / Array construction , Array expression or string On the grammatical level ; You can also construct objects , Press the object expression key-value The way to unfold .

grammar

Function call :
myFunction(...iterableObj); 
Array construction or string :
[...iterableObj, '4', ...'hello', 6]; 
When constructing objects , Clone or copy properties (ECMAScript 2018 What's new in the specification ):
let objClone = { ...obj }; 

Application scenarios

Use the extension operator when calling a function
function sum(x, y, z) {
  return x + y + z;
}
const numbers = [1, 2, 3];

// Don't use the extension operator 
console.log(sum.apply(null, numbers));

// Use the extension operator 
console.log(sum(...numbers));// 6 
Construct an array

When there's no unwrapping grammar , Can only be used in combination with push,splice,concat Other methods , To make an existing array element part of a new array . With unfolding grammar , It's easier to construct a new array 、 More elegant :

const stuendts = ['Jine','Tom']; 
const persons = ['Tony',... stuendts,'Aaron','Anna'];
conslog.log(persions)// ["Tony", "Jine", "Tom", "Aaron", "Anna"] 

Similar to the expansion of parameter list , ... When constructing word groups , It can be used at any position many times .

Array copy
var arr = [1, 2, 3];
var arr2 = [...arr]; //  Equate to  arr.slice()
arr2.push(4); 
console.log(arr2)//[1, 2, 3, 4] 

Expand grammar and Object.assign() Act in concert , It's all shallow copies ( Just one level ).

Connect multiple arrays
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
var arr3 = [...arr1, ...arr2];//  take  arr2  All elements in are attached to  arr1  Back and back 
// Equate to 
var arr4 = arr1.concat(arr2); 

stay ECMAScript 2018 The extension operators in add support for objects

var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };

var clonedObj = { ...obj1 };
//  The cloned object : { foo: "bar", x: 42 }

var mergedObj = { ...obj1, ...obj2 };
//  The combined object : { foo: "baz", x: 42, y: 13 } 

stay React Application in

Usually when we encapsulate a component , It will be more open to the public props Used to implement functions . In most cases, the transmission that should be displayed should be used externally props . But when delivering a lot of props when , It will be very complicated , Now we can use ...( Extension operator , Used to fetch all traversable properties of parameter object ) To deliver .

In general, we should write like this

<CustomComponent name ='Jine' age ={21} /> 
Use ... , It's the same as the above
const params = {
        name: 'Jine',
        age: 21
    }

<CustomComponent {...params} /> 
Cooperate with deconstruction assignment to avoid passing in some unnecessary parameters
var params = {
    name: '123',
    title: '456',
    type: 'aaa'
}

var { type, ...other } = params;

<CustomComponent type='normal' number={2} {...other} />
// Equate to 
<CustomComponent type='normal' number={2} name='123' title='456' /> 

8. Object attribute shorthand

stay ES6 We are allowed to set an object's property without specifying the property name .

Don't use ES6
const name='Ming',age='18',city='Shanghai';
        
const student = {
    name:name,
    age:age,
    city:city
};
console.log(student);//{name: "Ming", age: "18", city: "Shanghai"} 

Object must contain properties and values , It's very redundant .

Use ES6
const name='Ming',age='18',city='Shanghai';
        
const student = {
    name,
    age,
    city
};
console.log(student);//{name: "Ming", age: "18", city: "Shanghai"} 

Object , Very concise .

9.Promise

Promise Is a solution to asynchronous programming , More than traditional solutions callback More elegant . It was first proposed and implemented by the community ,ES6 It's written into the language standard , Unify usage , Native provides Promise object .

Don't use ES6

Nest two setTimeout Callback function :

setTimeout(function()
{
    console.log('Hello'); // 1 Second output "Hello"
    setTimeout(function()
    {
        console.log('Hi'); // 2 Second output "Hi"
    }, 1000);
}, 1000); 
Use ES6
var waitSecond = new Promise(function(resolve, reject)
{
    setTimeout(resolve, 1000);
});

waitSecond
    .then(function()
    {
        console.log("Hello"); // 1 Second output "Hello"
        return waitSecond;
    })
    .then(function()
    {
        console.log("Hi"); // 2 Second output "Hi"
    }); 

The code above uses two then For asynchronous programming serialization , Avoiding a callback to hell :

10. Support let And const

Before JS There is no block level scope ,const And let Fill in this convenient gap ,const And let It's all block scope .

Use var The variables defined are function level scopes :
{
  var a = 10;
}

console.log(a); //  Output 10 
Use let And const The variables defined are block level scopes :
{
  let a = 10;
}

console.log(a); //-1 or Error“ReferenceError: a is not defined” 

ES7 Characteristics of

stay ES6 after ,ES More frequently , Basically once a year , So from ES6 after , Each new version has fewer features .

  • includes()
  • Exponential operators

1. Array.prototype.includes()

includes() Function to determine whether an array contains a specified value , Return if included true, Otherwise return to false.

includes Function and indexOf Functions are very similar , The following two expressions are equivalent :

arr.includes(x)
arr.indexOf(x) >= 0 

Next, let's determine whether there is an element in the number :

stay ES7 Previous practice

Use indexOf() Verify that an element exists in the array , In this case, you need to determine whether the return value is -1 To judge :

let arr = ['react', 'angular', 'vue'];

if (arr.indexOf('react') !== -1)
{
    console.log('react There is ');
} 
Use ES7 Of includes()

Use includes() Verify that an element exists in the array , This is more intuitive and simple :

let arr = ['react', 'angular', 'vue'];

if (arr.includes('react'))
{
    console.log('react There is ');
} 

2. Exponential operators

stay ES7 Index operator is introduced in **,** Have and Math.pow(..) Equivalent calculation result .

Don't use the exponential operator

Use custom recursive functions calculateExponent perhaps Math.pow() Do an exponential operation :

function calculateExponent(base, exponent)
{
    if (exponent === 1)
    {
        return base;
    }
    else
    {
        return base * calculateExponent(base, exponent - 1);
    }
}

console.log(calculateExponent(2, 10)); //  Output 1024
console.log(Math.pow(2, 10)); //  Output 1024 
Use the exponential operator

Use the exponential operator **, It's like +、- Wait for the operator :

console.log(2**10);//  Output 1024 

ES8 Characteristics of

  • async/await
  • Object.values()
  • Object.entries()
  • String padding
  • Comma is allowed at the end of function parameter list
  • Object.getOwnPropertyDescriptors()

Browser compatibility

1.async/await

stay ES8 Added right async/await Support for , As far as we're concerned An asynchronous function , This is a very practical function . async/await Free us from the hell of headache , Make the whole code look simple .

Use async/await And no use async/await The difference between :
login(userName) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('1001');
        }, 600);
    });
}

getData(userId) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (userId === '1001') {
                resolve('Success');
            } else {
                reject('Fail');
            }
        }, 600);
    });
}

//  Don't use async/await ES7
doLogin(userName) {
    this.login(userName)
        .then(this.getData)
        .then(result => {
            console.log(result)
        })
}

//  Use async/await ES8
async doLogin2(userName) {
    const userId=await this.login(userName);
    const result=await this.getData(userId);
}

this.doLogin()// Success
this.doLogin2()// Success 

async/await Several application scenarios of

Let's take a look at async/await Several application scenarios of .

Get the return value of the asynchronous function

The asynchronous function itself returns a Promise, So we can pass then To get the return value of an asynchronous function .

async function charCountAdd(data1, data2) {
    const d1=await charCount(data1);
    const d2=await charCount(data2);
    return d1+d2;
}
charCountAdd('Hello','Hi').then(console.log);// adopt then Get the return value of the asynchronous function .
function charCount(data) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(data.length);
        }, 1000);
    });
} 
async/await Applications in concurrent scenarios

For the above example , We call await two , Every time I wait 1 The second is 2 second , Low efficiency , And twice await There is no dependency on the call to , Can we have it executed concurrently , The answer is yes , Next we pass Promise.all To achieve await Concurrent calls to .

async function charCountAdd(data1, data2) {
    const [d1,d2]=await Promise.all([charCount(data1),charCount(data2)]);
    return d1+d2;
}
charCountAdd('Hello','Hi').then(console.log);
function charCount(data) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(data.length);
        }, 1000);
    });
} 

Through the above code, we have implemented it twice charCount Concurrent calls to ,Promise.all It takes an array , It can change the array of promise Object concurrent execution ;

async/await Several ways to deal with errors

The first one is : Capture the whole thing async/await Error in function

async function charCountAdd(data1, data2) {
    const d1=await charCount(data1);
    const d2=await charCount(data2);
    return d1+d2;
}
charCountAdd('Hello','Hi')
    .then(console.log)
    .catch(console.log);// Capture the whole thing async/await Error in function 
... 

This way you can capture the whole thing charCountAdd Errors in the running process , The mistake may be due to charCountAdd Of itself , It may also be due to the fact that data1 In the calculation of data2 From the calculation of .

The second kind : Capture individual await Error in expression

async function charCountAdd(data1, data2) {
    const d1=await charCount(data1)
        .catch(e=>console.log('d1 is null'));
    const d2=await charCount(data2)
        .catch(e=>console.log('d2 is null'));
    return d1+d2;
}
charCountAdd('Hello','Hi').then(console.log); 

In this way, you can capture every one of them await Error in expression , If you want to capture every one of them await Error in expression , And capture the whole thing charCountAdd Error in function , You can call charCountAdd Add one when it's time catch.

...
charCountAdd('Hello','Hi')
    .then(console.log)
    .catch(console.log);// Capture the whole thing async/await Error in function 
... 

The third kind of : Capture more than one at a time await Error in expression

async function charCountAdd(data1, data2) {
    let d1,d2;
    try {
        d1=await charCount(data1);
        d2=await charCount(data2);
    }catch (e){
        console.log('d1 is null');
    }
    return d1+d2;
}
charCountAdd('Hello','Hi')
    .then(console.log);

function charCount(data) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(data.length);
        }, 1000);
    });
} 

2.Object.values()

Object.values() It's a relationship with Object.keys() Similar new functions , But back to Object All values of self attributes , Does not include inherited values .

Let's say we're going to traverse the following objects obj All values :

const obj = {a: 1, b: 2, c: 3}; 
Don't use Object.values() :ES7
const vals=Object.keys(obj).map(key=>obj[key]);
console.log(vals);//[1, 2, 3] 
Use Object.values() :ES8
const values=Object.values(obj1);
console.log(values);//[1, 2, 3] 

As you can see from the above code Object.values() It saves us from traversal key, And according to these key obtain value Steps for .

3.Object.entries

Object.entries() Function returns an array of key value pairs of enumerable properties of a given object .

Now let's go through the above obj Of all properties of an object key and value:

Don't use Object.entries() :ES7
Object.keys(obj).forEach(key=>{
    console.log('key:'+key+' value:'+obj[key]);
})
//key:a value:1
//key:b value:2
//key:c value:3 
Use Object.entries() :ES8
for(let [key,value] of Object.entries(obj1)){
    console.log(`key: ${key} value:${value}`)
}
//key:a value:1
//key:b value:2
//key:c value:3 

4.String padding

stay ES8 in String Two instance functions are added String.prototype.padStart and String.prototype.padEnd, Allows an empty string or other string to be added to the beginning or end of the original string .

String.padStart(targetLength,[padString])
  • targetLength: The target length to which the current string needs to be filled . If this value is less than the length of the current string , Returns the current string itself .
  • padString:( Optional ) Fill string . If the string is too long , Make the length of the filled string exceed the target length , Only the leftmost part , The rest will be cut off , The default value of this parameter is " ".
console.log('0.0'.padStart(4,'10')) //10.0
console.log('0.0'.padStart(20))//                0.00 
String.padEnd(targetLength,padString])
  • targetLength: The target length to which the current string needs to be filled . If this value is less than the length of the current string , Returns the current string itself .
  • padString:( Optional ) Fill string . If the string is too long , Make the length of the filled string exceed the target length , Only the leftmost part , The rest will be cut off , The default value of this parameter is " ";
console.log('0.0'.padEnd(4,'0')) //0.00 
console.log('0.0'.padEnd(10,'0'))//0.00000000 

4. Comma is allowed at the end of function parameter list

This is a painless update , The main function is to facilitate the use of git Modify the same function to reduce unnecessary line changes during multi-user collaborative development .

Don't use ES8
// The programmer A
var f = function(a,
  b
   ) { 
  ...
  }

// The programmer B
var f = function(a,
  b,   // Change line 
  c   // Change line 
   ) { 
  ...
  }

// The programmer C
var f = function(a,
  b,
  c,   // Change line 
  d   // Change line 
   ) { 
  ...
  } 
Use ES8
// The programmer A
var f = function(a,
  b,
   ) { 
  ...
  }

// The programmer B
var f = function(a,
  b,
  c,   // Change line 
   ) { 
  ...
  }

// The programmer C
var f = function(a,
  b,
  c,
  d,   // Change line 
   ) { 
  ...
  } 

5.Object.getOwnPropertyDescriptors()

Object.getOwnPropertyDescriptors() Function to get the descriptors of all the properties of an object , If there is no self property , Then return the empty object .

The function prototype :
Object.getOwnPropertyDescriptors(obj) 

return obj Descriptors for all of the object's own properties , If there is no self property , Then return the empty object .

const obj2 = {
    name: 'Jine',
    get age() { return '18' }
};
Object.getOwnPropertyDescriptors(obj2)
// {
//   age: {
//     configurable: true,
//     enumerable: true,
//     get: function age(){}, //the getter function
//     set: undefined
//   },
//   name: {
//     configurable: true,
//     enumerable: true,
//      value:"Jine",
//      writable:true
//   }
// } 

summary

The wheel of technological change is always moving forward ,JavaScript Standards and standards are also in constant development and improvement . You'll find that ECMAScript Many of the features of the new version are already Typescript, Browser or something polyfills Part of , take ES8 Of async/await Come on , It is 2017 year 6 Month included ECMAScript Of , But I was 2016 This feature has been in use since 1980 , These features are usually made up of ECMAScript Members present , And then it will appear in some future ECMAScript In the version .

Reference resources

Related articles

  1. ES2020 in Javascript 10 New features you should know about
  2. To relive ES6 Core concepts and basic usage

Last , Welcome to my official account. : Front end development blog , reply Add group , Learn together .

版权声明
本文为[Front end development blog]所创,转载请带上原文链接,感谢