ES6 key knowledge summary

Keywords: Javascript html5 Vue.js

The most important and complex knowledge points of ES6: 1. Class and inheritance 2.promise 3. ES6 modularization (in vue)

Knowledge points related to deep copy

  1. Object.assgin() method: it can realize the deep copy of the first layer object
  2. Simple and crude deep copy

  1. Complete deep copy: refer to online materials

Common array methods

The following methods have callback functions. The two formal parameters of the callback are item value and index respectively
return is required for all methods except forEach

  1. arr.forEach()
  3. arr.filter()
  4. arr.some()
  5. arr.every()
  6. arr.reduce()

let: declare block level scope

  • There is no problem of declaration in advance
  • Declaration cannot be repeated in the same block
  • The correct index can be obtained through let

    let arr = []
    for (let i = 0; i < 6; i++){
        arr[i] = function(){

const: declare constants

  • const is also a block level scope
  • Assignment is required at the same time of declaration

Arrow function


let fun = ()=>{}
let fun = x => {}
let fun = (x,y) => {}
let fun = (x,y) => 3
let fun = (x,y) => ({
        name: 1,
        age: 2

this of the arrow function points to

The arrow function itself does not have this. Its internal this is the this that defines the environment where the arrow function is located

        box.onclick = function(){
            // console.log(this);
            let i  = 0
                this.innerHTML = i;  //this is box

Shorthand for object literals

    let color = 'red',
        age = 18;

    let obj = {

Classes and inheritance

Define parent class

class Animal {
        this.type = 'animal';
        this.eye = true;
        this.color = color;

var ani = new Animal('red')

Define subclasses

class Cat extends Animal{
        this.nickname = nickname;
        this.age = age;
var cat = new Cat('little cat',5,'white')

Template string

    let color = 'red';
    let str = `this is ${color}`

Destructuring assignment

    let obj = {
            title: 'aaaa',
            price: 300,
            discount: 200

    let {title,price} = obj;

Expand operator

Break up the values in the array and list them one by one

        let arr = [34, 56, 78];

        function total(Ch, En, Math) {
            return Ch + En + Math;
        let result = total(...arr)

        let divList = document.querySelectorAll("div");

        //A pseudo array can call forEach, but cannot call the traversal methods of other arrays

        var arr = [...divList].map((el)=>{
            return el.innerHTML

Default parameters

        function draw(radius=100){

        // The default parameter must be set last
        function draw(y,x=2,z=20){


Remaining parameters

        function total(...args){
            console.log(args instanceof Array);  //true

Symbol data type

The only variable that will not be repeated is the basic data type added in ES6

        // Application scenario of Symbol

        //An object is defined in a third-party library (hidden to users)

        let obj = {
            name: '23',
            count() {

        // Extend the function of the object: you want to use an attribute name that will not duplicate the existing attributes of the object

        let count = Symbol();

        obj[count] = function(){

        obj.count()  // count
        obj[count]();  //quantity

Data of type Set

Is the data type of the collection newly added in ES6, which is used to store arrays. However, the elements of an array cannot be repeated

Array de duplication

    var arr = [1,2,3,2,5,1]
    var result = [ Set(arr)]

Set common API s

        1. add
        2. delete
        3. has
        4. clear

for...of statement

  • for: (1) you need to specify the number of traversals; (2) you can't traverse the object, you can traverse the collection array other than the object, and the pseudo array (3) you can use break and continue
  • forEach: (1) you can traverse collections other than objects (array, set, NodeList - > DOM Collection) (2) you cannot use break and continue
  • (1) traverses the object (2) cannot directly access the attribute value of the object (3) (3) break and continue can be used
  • New for...of:
    (1) for...of cannot be used for custom objects, but most native data sets can be used (array, string, Set type, Map type, NodeList)
    (2) You can use break and continue

    //Act on array
    var arr = ['a','c','d']
        for(let i of arr){

//NodeList acting on element node
    let divList = document.querySelectorAll("div");
        for (let el of divList){

Object API

  1. Object.assign: merge objects
  2. Object.keys(): returns a collection of all keys of an object

        let obj = {
            name: 'Peppa',
            age: 4,
            sex: 'female'
        // ["name","age","sex"]

Map type data

Similar to an object, it is used to store key value pairs.

Objects can only use strings as attribute names, while maps can use any type of data as attribute names

//The first key is "a" with a value of 1, and the second key is b with a value of 2
        var map1 = new Map([["a",1],["b",2]]);

API for Map

        attribute: size 
        method: set , get , has, delete ,clear

for...of traversal

    var map1 = new Map([["a", 1], ["b", 2]]);
        //Traverse keys only
        for (let key of map1.keys()){

        // Traversal values only
        for (let val of map1.values()){

        // val is an array that stores the key and value of each
        for (let val of map1){

        //Return key value pairs at the same time
        for (let [key,value] of map1){

        // Equivalent to the above writing
        for (let [key,value] of map1.entries()){


  • promise is used to solve the problem of callback hell and implement asynchronous code in a synchronous way

  • Promise is a solution for asynchronous programming, which is more reasonable and powerful than traditional solutions - callback functions and events.
    It was first proposed and implemented by the community. ES6 has written it into the language standard, unified the usage, and provided Promise objects natively.

  • Three states of a Promise
    pending: initial state, which is neither successful nor failed.
    Fully: indicates that the operation completed successfully.
    rejected: means the operation failed.

  • The Promise constructor accepts a function as an argument. The two parameters of the function are resolve and reject. They are two functions provided by the JavaScript engine and do not need to be deployed by themselves.
    The Resolve function is used to change the state of the Promise object from "incomplete" to "successful" (that is, from pending to resolved), call it when the asynchronous operation is successful, and pass the result of the asynchronous operation as a parameter;
    The Reject function is used to change the state of the Promise object from incomplete to failed (that is, from pending to rejected), call it when the asynchronous operation fails, and pass the error reported by the asynchronous operation as a parameter.

  • After the Promise instance is generated, you can use the then method to specify the callback functions in the resolved state and the rejected state respectively.

        // Requirements: execute ajax2 after ajax1 is executed, and task after ajax2 is executed
        function ajax1() {
            setTimeout(function () {
            }, 1000)
        function ajax2() {
            setTimeout(function () {
            }, 2000)
        function task() {

Implemented with Promise

       var flag1 = true;
       var flag2 = false;

       function error(err) {
       function ajax1() {
           return new Promise((resolve, reject) => {
               setTimeout(function () {
                   if (flag1) {
                       resolve('ajax1 Results')
                   } else {
                       reject('ajax1 error')
               }, 1000)

       function ajax2(data) {
           return new Promise((resolve, reject) => {
               setTimeout(function () {
                   console.log('ajax2 receive ajax1 Parameters of', data);
                   if (flag2){
                       reject('ajax2 error')
               }, 2000)

       function task() {


Promise.all() Promise.race()

Promise.all() the logic to execute after both asynchronous operations are successfully completed
Promise.race() the asynchronous operation that gets the result first is executed successfully, that is, the following logic is executed
Parameters in all() and race() must be promise instances

               console.log('Data after both requests are successful',data);

   Promise.race([ajax1(), ajax2()])
           .then(function (data) {
               console.log('Request to return the result of the fastest task', data);

Usage of async and await

  • async: define an asynchronous function, eliminate the chain call of then in promise, and make the code clearer and elegant
  • await is followed by a function that returns new promise and executes it
  • await can only be placed in async functions
  • The async function handles the logic to be executed in case of failure through try...catch

    var flag1 = false;
        var flag2 = true;
        function ajax1() {
            return new Promise((resolve, reject) => {
                setTimeout(function () {
                    console.log('ajax1 The task is completed');
                    if (flag1) {
                        resolve('ajax1 Results')
                    } else {
                        reject('ajax1 error')
                }, 1000)
        function ajax2(data) {
            return new Promise((resolve, reject) => {
                setTimeout(function () {
                    console.log('ajax2', data);
                    console.log('ajax2 The task is completed');
                    if (flag2) {
                        resolve('ajax2 Results')
                    } else {
                        reject('ajax2 error')
                }, 2000)
        function task(data) {
            console.log('task The task is completed');
            console.log('task', data);

        async function render() {
            try {
                let result1 = await ajax1()
                await ajax2(result1)


Define the properties of the object

let obj = {
    name: 'Journey to the West',
    addTime: '739754975945489'

//You must use a temporary variable to store the value of the name attribute
let temp =;

// Interceptor
    get: function(){
        //There must be a return in get. The result of return is the new value of the name attribute
        return "<" + temp + ">"
    set: function(newVal){
        temp = newVal;
}) = "Bean by the window";


Posted by WindomEarle on Wed, 06 Oct 2021 22:32:36 -0700