ES6 syntax features

1.ES6 new syntax features

1. Comparison of the way ES5 and ES6 declare variables
The way to declare variables in ES5:

//1. Through var declaration
var num;

//2. Function declaration
function fn(num){ return num; }
fn(10);

The way to declare variables in ES6:

//1. Use the let statement
let a = 10;

//2. Use const declaration
const name = "little red";

2. The difference between var, let and const:

1. There is no variable hoisting

  • The variable promotion phenomenon occurs in the var command, that is, the variable can be used before the declaration, and the value is undefined. let and const
    Then there is no function of variable declaration promotion, and it must be declared before it can be used

2. Duplicate statements are not allowed

  • The var command can repeat the statement, the latter overrides the former
  • let and const are not allowed to declare the same variable repeatedly in the same scope

3. Scope

  • The scope of var is bounded by the function
  • The scope of let and const is block scope, and block-level scope refers to the scope within { }
  • var can define global variables and local variables, let and const can only define local variables
  • The declared constant of const cannot be modified, but for reference type, the value in the heap memory can be changed.

4. Variables as global attributes
The defined variable will be used as the property of the window object, let will not

The reference type defined by the constant can be modified, such as:

//1. Use constants to define arrays
        const arr = [100, 200, 300];
        console.log(arr);

        arr[0] = "hello";
        console.log(arr);   //['hello', 200, 300]

        //2. Use constants to define objects
        const obj = {
            name: "Jack",
            age: 22,
            no: "001"
        }
        console.log(obj);

        obj.age = 100;
        console.log(obj);   //{name: "Jack", age: 100,  no: "001"}

3. Temporary dead zone

Definition: When there is a let command in the block-level scope, the declared variable is "bound" to this area and is no longer affected by the outside.

{
    //The area before let a becomes a temporary dead zone, calling a will report an error
    let a = "hello";
}

4. Scope problem in for loop

//The part where the loop variable is set is the parent scope, and inside the loop body is a separate child scope.
//Reference variables in ES6 adopt the principle of proximity

5. Deconstruction of variables

Essence: pattern matching
   1. Full destructuring: the pattern matches exactly
   2. incomplete deconstruction: the pattern does not match exactly

   - Set a default value for a destructured variable that does not appear undefined The phenomenon
   - When destructuring is successful, the default value of the destructuring variable will be overwritten
   - When the destructuring is unsuccessful, the value of the destructuring variable is the default value
   
  Note on object deconstruction:
    1.When the object is destructured, the variable name must be consistent with the property name
    2.Destructuring variables for object destructuring regardless of order
    3.When the object is deconstructed, rename the object property, which can facilitate the writing of the program. Note: renaming does not change the properties of the object
    4.As with destructuring arrays, default values ​​can be set when parsing objects outLookURL:url = 111

6. The function adds the default value of the parameter

1. Use destructuring to pass parameters and set default values ​​for parameters   //show({ name = 'lucy', age = 22 } = {})  
                                 //show([a = 0, b = 0])
2. ES6 Add default values ​​directly to parameters     //show(a = 0, b = 0)`

7.rest parameters

rest Parameters: receive variable parameters
1. rest parameter is a way(Formal parameter),rest Parameters can be renamed to other parameters ...a
2. rest parameter can only be used as the last parameter

8. Two methods of function definition in ES5:

1. Functional       //var fn = function(){}
2. Declarative       //function show(){}

9. Arrow functions in ES6

ES6 Arrow function => replace
 Arrow functions: use => define function

1. When the function has no parameters, () cannot be omitted
2. When the function has only one parameter, and the function body is a code, and it is a return statement
3. The () of the parameter can be omitted, the function body {} can be omitted, the return can be omitted,
4. Use => connection in the middle
5. If the function body has only one sentence, and it is not a return statement, {} cannot be omitted
6. If there are multiple statements in the function body, {} cannot be omitted
7. If the function has multiple parameters, () cannot be omitted
8. If the return value of the function is an object, return cannot be omitted at this time

Note on using arrow functions:

Arrow functions do not work with declared functions
Arrow functions don't work with DOM events
Arrow functions cannot be used as constructors (iterators)
arguments cannot be used inside an arrow function
Cannot use yield command

10. The arrow function this points to

The arrow function does not have this, this is the parent's
When it is defined, it is bound, that is, this is inherited from the parent execution context! ! this in
In ES5, this refers to the caller, in ES6, this refers to the binding at the time of definition

11. String traversal

    let str = "hello";
    //1.for traversal
    for (let i = 0; i < str.length; i++) {
        console.log(i, str[i]);     //i index value type
    }
    
    //2. Array->for->for in
    let arr = [1, 2, 3];
    for (let i in arr) {
        console.log(i, arr[i]);     //i index string type
    }
    
    //3.for... of
    for(let i of str){
        console.log(i);     //data
    }
    
    //4. Deconstruction
    let [a, b, c, d ,e] = str;
    console.log(a, b, c, d ,e);

12.ES6 new string method

//String method:
method                return value          effect
includes('str')     boolean         Determine whether a string contains a substring
endWith('str')      boolean         Judgment string with"str"end
startWith('str')    boolean         Judgment string with"str"beginning
repeat(n)           repeat splicing itself     repeat n secondary output string repeat + repeat

//Incomplete method: complete string length
padStart(length, s);        Completion at the beginning of the string
endStart(length, s);        End of string completion

13.ES6 Template Strings

template string backticks ``

1. Support newline //Blank will be printed out
2. Pass variables in the template ${variable}

    let obj = {
        name: 'jack',
        age: 20
    };
    console.log(`name: ${obj.name},age: ${obj.age}`);  //Name: jack, age: 20

14.ES6 Extensions for Objects

Object extension:

  //1. Abbreviation of the attribute of the object: When the attribute name of the object is consistent with the attribute value (variable) name, the assignment can be omitted
    //2. Object method shorthand:
    let name = "jack";
    let age = 22;

    let obj = {
        name,
        age,
        walk: function () {
            console.log(this.name + " is walk");
        },
        say() {
            console.log(this.name + ` say`);
        }
    }

15. The Set structure of ES6

set structure: elements in this structure are unique and cannot be repeated

method: the return value is set can be linked
    add(val)           Add elements
    delete(val)        delete element
    has(val)           Determine whether to contain elements     boolean
    clear()            delete all data

Attributes:
    size    number of elements

use new Set()instantiate

Traversal of the set structure

for of traverse set
for of traverse keys()
for of traverse values()
for of traverse object entity entries
forEach traverses the set
Use the spread operator and destructuring to convert the set structure into an array

    // for of traverse data
    for (let i of set) {
        console.log(i);     //1  2  5  3
    }
   
    // Traversing keys is equal to traversing set
    for (let i of set.keys()) {
        console.log(i);
    }

    //traverse values
    for (let i of set.values()) {
        console.log(i);
    }

    //Traverse object entity entries
    for (let i of set.entries()) {
        console.log(i[0]);
    }
    
    //Traversing object entities in a deconstructed way
    for (let [k, v] of set.entries()) {
        console.log(k, v);
    }

    // for each traverse set
    set.forEach(i => {
        console.log(i);
    })

16. Map structure of ES6

Map structure: Since the properties of objects can only accept string types, a Map structure is generated to optimize the object structure

method: the return value is Map Instances can be chained
    set(key,val)        Add elements
    get(key)            take elements
    has(key)            Determine whether to contain elements     boolean
    clear()             delete all data

use new Map()instantiate
  // 1. Add data set()
    map.set('name', 'jack').set('age', 22).set(0,100);
    console.log(map);

    // 2. Get data get()
    console.log(map.get(0));        //100
    console.log(map.get('name'))    //jack

    // 3. Judging the existence of data has()
    console.log(map.has(0));        //true

    // 4. Delete data delete()
    map.delete(0);
    console.log(map);       //Map(2) {"name" => "jack", "age" => 22}

    // 5. Empty data clear()
    map.clear();
    console.log(map);       //Map(0) {}

Map structure rules

    //1. map supports arrays as constructor parameters, but it must be a two-dimensional array
    // let arr = [1, 2, 3, 4, 5];  //Iterator value 1 is not an entry object
    let arr = [['name', 'jack'], ['age', 23]];
    let map = new Map(arr);
    console.log(map);   //Map(4) {"name" => "jack", "age" => 23}


    // 2. The key cannot be repeated, but the val can be repeated. If the key is repeated, the original value will be overwritten
    map.set('name','tom');
    map.set('hob','sing');
    console.log(map);   //Map(5) {"name" => "tom", "age" => 23, "hob" => "sing"}

Map traversal

let of traverse the map
forEach traverses the map
let of traverse map.keys
let of traverse map.values
let of traverse map.entries
let of traverse map.entries + destructure

 // 1.let of traverse the map
    for (let i of map) {
        console.log(i[0], i[1]);
    }
   
    // 2.foreach traverses the map
    map.forEach((v, k) => {
        console.log(k, v);
    })
  
    // 3.let of traverse map.keys
    for (let k of map.keys()) {
        console.log(k, map.get(k));
    }
    
    // 4.let of traverse map.values
    for (let v of map.values()) {
        console.log(v);
    }
    
    // 5.let of traverse map.entries
    for (let i of map.entries()) {
        console.log(i[0], i[1]);
    }
    
    // 6.let of traverse map.entries + destructure
    for (let [k, v] of map.entries()) {
        console.log(k, v);
    }

16. Conversion between set structure and map structure type of ES6

Set and array
    1.set -> array
        1.Array.from();
        2.traverse set Then push
        3.spread operator

    2.array -> set
        1.new Set(arr);
    
Map and object and string
    1.map -> object -> String
        1.forEach traverse Map -> object -> JSON.stringify
    2.String -> object -> map
        1.JSON.parse -> object -> for...in traverse objects -> Map.add()

Between Set and Array

let set = new Set();
set.add(1).add(2).add(3).add(2);

// 1.Array.from();
var arr = Array.from(set);
console.log(arr);

// 2. Traverse set and then push
var arr  = [];
set.forEach(i=>{
    arr.push(i);
});
console.log(arr);

// 3. Spread operator
var arr = [...set];
console.log(arr);

between map, object and string

let map = new Map();
map.set('name', 'jack').set('age', 22).set('tel', 151);

// 1. map -> Object -> String
var obj = {};
map.forEach((v,k)=>{
    obj[k] = v;
})
console.log(obj);

var str = JSON.stringify(obj);
console.log(str);

// 2. String -> Object -> map
var obj1 = JSON.parse(str);
var map1 = new Map();
for(let i in obj1){
    map1.set(i,obj1[i]);
}
console.log(map1);

16. The difference between rest and spread operator

The rest parameter appears in the position of the function parameter

Function: discrete data -> array

function fn(...rest) {
    console.log(rest);
}
fn(100, 110, 120);    //(3) [100, 110, 120]

... the spread operator occurs in a non-argument position

effect:
array -> discrete data
Split pseudo-array: NodeList HTMLCollection arguments…

let arr = [1, 2, 3, 4, 5];
console.log(...arr);    //1 2 3 4 5    

function fn1() {
    console.log(arguments);     //Arguments(3) [2, 3, 4]
    console.log(...arguments);  //2 3 4
}
fn1(2,3,4);

17.ES6 object-oriented

17-1, class class, template

Constructor: When the class is instantiated, the constructor is automatically executed
Each class must have at least one constructor, if not, the system will automatically add a no-argument constructor
Constructor, cannot be called actively

17-2, set and get set and get properties

get cannot pass parameters
The get method can only be written when there is a set method, and it appears at the same time

17-3. Static method:

The method of the class itself can be called without instantiation
Will not be inherited by the instance, called directly through the class

17-4. Static attributes:

classname.propertyName = value;

17-5. extends implements inheritance

Inheritance is one-way
The inherited class belongs to the parent class, the base class, also known as the super class
Static methods can be inherited by subclasses
The inherited attribute super() must be placed in the first sentence of the constructor
A parent class can have multiple subclasses, and a subclass has only one parent class

17-6. Note:
The parent class can call its own member methods
The parent class can call its own static method
The parent class cannot call the member methods of the subclass

Instances of subclasses can call parent class member methods
Instances of subclasses cannot call parent class static methods
Subclasses can call parent class static methods

class Person {
    constructor(uname, uage) {
        this.uname = uname;
        this.uage = uage;
    }
    //member method
    walk() {
        console.log(`${this.uname}running!`);
    }

    // Static method: the method of the class itself
    static cry() {
        console.log('Born to cry!');
    }
}
// static property
Person.living = 'earth';


//The student class inherits from the Person class
class Student extends Person {
    constructor(sname, sage, sno) {
        super(sname, sage);  //This sentence must be in the first sentence of the constructor
        this.sno = sno;
    }

    // member method
    study() {
        console.log(`${this.sname}I'm studying!`);
    }
    
    //set accessor controls the setting of the property
    set sage(age) {
       
    }

    // get accessor, get property
    get sage() {
        
    }
}

//Create an instance of a class Instantiation of a class
var stu = new Student('Wang Sa', 23, '001');

18. Exception handling in JS

try...catch
try...finally
try...catch...finally

19.ES6 Promise solves callback hell

19-1, promise: generated to solve the callback hell in asynchronous programming

Promise An instance of needs to receive a function as an argument
 This function needs to receive two function numbers as parameters
resolve function
reject function

19-2. Three states of promise

pending processing
fullfilled succeeded resolved successful execution resolve function
rejected failed rejected fail to execute reject function

19-3. then method

Parameter one: Yes resolve function implementation
 Parameter two: Yes reject function implementation

19-4. The return value of the then method is a new Promise instance
Note that it is not the original Promise instance

If the previous callback function returned a Promise object (i.e. with asynchronous operations),
The latter callback function will wait for the Promise Called when the state of the object changes.

19-5. Exception handling of promise
It is recommended to always use the catch method.
Promise errors have a "bubbling" nature and are propagated backwards until caught.
Once the state of a Promise is changed, it will remain in that state forever and will not change again.
The catch method returns a Promise object
When catch and reject appear at the same time, only reject is executed
19-6. Multiple asynchronous operations

// load image function
function loadPic(id, src, sec) {
    return new Promise((resolve, reject) => {
        let oImg = new Image();
        oImg.onload = function () {
            resolve(oImg);
        }
        oImg.onerror = function () {
            reject(`No ${id}task failed for`);
        }
        // oImg.src = src;
        setTimeout(() => {
            oImg.src = src;
        }, sec);   //Lazy loading functions
    })
}

let s1 = "remote picture";
let s2 = "remote picture";
let p1 = loadPic('001', s1, 1000);
let p2 = loadPic('002', s2, 100);

// Promise.all method
// When all the pictures are loaded, follow-up actions are executed, and if one fails, then will not be executed
let p = Promise.all([p1, p2]);  //all returns the new promise object
p.then(data=>{
    console.log(data,'Loaded successfully');
    document.body.append(data[0],data[1]);
}).catch(err=>{
    console.log(err);
}).finally(()=>{
    console.log('Whether successful or not, I execute');
}); 


// Promise.race method
// Note:
//  1. As long as a picture is loaded, execute the resolve implementation of then
//  2. If the image loaded first fails, the subsequent image will not be loaded, and catch or reject will be executed directly

let p = Promise.race([p1, p2]);
p.then(data => {
    console.log(data);      //Only return the one that loaded successfully first
    document.body.append(data);    //Since the delay is set, the second one is loaded first
}).catch(err => {
    console.log(err);
})

20.ES module import rules

error prone place

1. The page does not run based on the server, and there will be cross-domain errors
origin 'null' has been blocked by CORS policy: Cross origin requests are only

2. When using modularization, a syntax error will occur if the page does not add type = "module"
app.js:1 Uncaught SyntaxError: Unexpected token {

<script src="./module/app.js" type="module"></script>

3. If the suffix name of .js is not added when importing the module, it will report that the module cannot be found error
GET xxx net::ERR_ABORTED 404 (Not Found)

import { Student } from './Student.js';

Import and export method

1. Export method

  • export when defined
  • batch export
  • export rename (not recommended)
  • export by default
    // 1. Export at definition time
    export let uname = 'Li Si';
    
    export function showStudentName(){
        console.log(uname);
    }
    
    export class SomeAnimalInfo{
        constructor(type,age){
            this.type = type;
            this.age = age;
        }
        showInfo(){
            console.log(`species:${this.type},age: ${this.age}`);
        }
    }
    
    // 2. Batch export
    const PI = 3.1415926;
    const DBNAME = 'Local';
    ... ...
    
    export { PI, DBNAME };
    
    // 3. Default export - tools
    export default class {
        static log(msg) {
            let now = new Date();
            console.log(`${now.toLocaleString()}    ${msg}`);
        }
        
        static setCookie(){
            
        }
        ... ...
    }

2. Import method

  • import rename
  • import the whole module
  • import default module
   //1. Import rename as syntax
    import {num, showStudentName as showName} from './all.js';
    
    // 2. To import the entire module, you need to use as to rename, and you receive an object
    import * as cons from './const.js';
    
    // 3. Import the default module needs to be named, the name contains the exported content
    import Tool from './tools.js';

Original author link: https://www.jianshu.com/p/d23a506cdca2

Tags: Front-end Javascript ECMAScript

Posted by myleow on Wed, 23 Nov 2022 07:58:10 +1030