ES6 grammar

How es5 and ES6 declare variables

How to declare variables in ES5:

//1. Declare using var
var num;

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

How to declare variables in ES6:

//1. Use the let declaration
let a = 10;
//2. Use const declaration
const name = "Little red";
Copy the code

Var, let, const

  1. There is no variable promotion
    • The var command will promote the variable, that is, the variable can be used before the declaration and its value is undefined
    • Let and const have no variable declaration enhancement and must be declared before they can be used
  2. Duplicate declarations are not allowed
    • The var command can be declared repeatedly, with the latter overwriting the former
    • Let and const are not allowed to declare the same variable twice in the same scope
  3. scope
    • The scope of var is function bound
    • The scope of let and const is block scope, and the block-level scope refers to the scope inside {}
    • Var can define global and local variables, while let and const can define only local variables
    • The declared constant of const cannot be modified, but for reference types, the value in heap memory can be changed.
  4. Variables as global properties
    • Variables defined by var are treated as properties of the window object, while let is not

** Constants define reference types that can be modified

//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"}
Copy the code

Temporary dead zone definition: when a let command exists in a block-level scope, the declared variable is “bound” to the region, no longer subject to external influence

{
    //let the area before a become a temporary dead zone
    let a = "hello";
}
Copy the code

Scope problems in the for loop

// The part that sets the loop variable is the parent scope, while inside the loop body is a separate child scope. // In ES6, reference variables use the proximity principleCopy the code

Deconstruction of variables

Essence: Pattern matching1.Complete deconstruction: Patterns match perfectly2.Incomplete deconstruction: Patterns do not match perfectly - set default values for deconstruction variables and do not appearundefinedIf the deconstruction succeeds, the default value of the deconstruction variable will be overwritten. If the deconstruction fails, the value of the deconstruction variable will be the default value.1.When an object is deconstructed, the variable name is the same as the attribute name2.Object deconstruction variables do not consider order3.When objects are deconstructed, the object attributes are renamed to facilitate the programming of programs. Note: Renaming does not change the properties of the object4.As with arrays, you can set the default value outLookURL when parsing objects: URL =111
Copy the code

The function adds the default value of the argument

1.Using deconstructed parameters, the parameters are set to default values//show({ name = 'lucy', age = 22 } = {})  
                            //show([a = 0, b = 0])

2.ES6 directly adds default values for parameters//show(a = 0, b = 0)
Copy the code

Rest parameters

Rest parameter: receives indefinite parameter --1.Rest parameters are one way (parameters) that rest parameters can be renamed to other parameters... a2.The REST parameter can only be used as the last parameterCopy the code

Es6 extensions to objects **

//1. Object attribute shorthand: When the object attribute name is the same as 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`); }}Copy the code

Arrow functions in ES6

Two methods of function definition in ES5

1.functional//var fn = function(){}
2.declarative//function show(){}
Copy the code

Functional declarations in ES6 are replaced by arrow functions (=>)

Arrow functions: Define functions using =>Copy the code
  1. When a function has no arguments, () cannot be omitted
  2. When a function has only one argument and the body of the function is a single line of code and is a return statement, the () of the argument can be omitted, the body of the function {} can be omitted, the return can be omitted, and the => concatenation is used
  3. If the function body has only one sentence and is not a return statement, do not omit {}.
  4. If the function body has more than one statement, do not omit {}
  5. If a function has more than one argument, do not omit ()
  6. If the function returns an object, do not omit return

Use the arrow function notice

  1. Arrow functions do not apply to declared functions
  2. Arrow functions do not apply to DOM events
  3. Arrow functions cannot be constructors (iterators)
  4. You cannot use arguments inside arrow functions
  5. You cannot use the yield command
The arrow function this points to
  1. Arrow functions don’t have this; this is parent
  2. The definition binding is that this is inherited from the parent execution context
  3. This in ES5 refers to the caller, and this in ES6 refers to the definition binding

String traversal

let str = "hello";
    / / 1. For traversal
    for (let i = 0; i < str.length; i++) {
        console.log(i, str[i]);     // I Index numeric 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);
Copy the code

ES6 added a string method

// String new method:Method returns the value includes('str'Boolean Check that the string contains the substring endWith('str') Boolean Determines the string as"str"The ending startWith ('str') Boolean Determines the string as"str"At the beginning repeat(n) repeats itself repeating n times outputs the string repeat + repeat// A method to complete the length of a stringpadStart(length, s); Complete the beginning of the string endStart(length, s); Complete the end of the stringCopy the code

Es6 template character string

The es6 template string is in backquotes

  • Support line
  • ${variable}
let obj = {
        name: 'jack'.age: 20
    };

console.log(` name:${obj.name}Age:${obj.age}`);  // Name: Jack, age: 20
Copy the code

Es6 Set structure

Set structure Elements in this structure are unique and cannot be repeated

usenew Set() instantiate method: return value is set can be add(val) plus elementdeleteBoolean clear() Delete all data attributes: size Number of elements Set traversal:1. for  ofTraverse the set2. for  ofTraversal keys ()3. for  ofTraverse the values ()4. for  ofIterate through object entity entries5.The forEach traverse the set6.Convert a set structure into an array using extension operators and destructionsCopy the code
// for traversal data
    for (let i of set) {
        console.log(i);     / / 1 2 3 5
    }
   
    // keys is set
    for (let i of set.keys()) {
        console.log(i);
    }
    / / traverse values
    for (let i of set.values()) {
        console.log(i);
    }
    // Iterate through object entity entries
    for (let i of set.entries()) {
        console.log(i[0]);
    }
    
    // Walk through object entities in a deconstructive manner
    for (let [k, v] of set.entries()) {
        console.log(k, v);
    }
    // for each traverses set
    set.forEach(i= > {
        console.log(i);
    })
Copy the code

Es6 Map structure

Map structure Since the attributes of the object can only accept strings, the Map structure is generated, and the object structure is optimized so that the Map Key can be used for any attribute

usenewMap() instantiation method: the return value is that Map instances can be concatenatedset(key,val) Add element get(key) Check whether element has(key) Boolean Clear () Delete all data// 1. Add data set()
    map.set('name'.'jack').set('age'.22).set(0.100);
    console.log(map);
    // 2. Get ()
    console.log(map.get(0));        / / 100
    console.log(map.get('name'))    //jack
    // 3. Check the presence 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. Clear data ()
    map.clear();
    console.log(map);       //Map(0) {}
Copy the code

Map structure rules

//1. Map supports arrays as constructors, but they must be two-dimensional arrays
// 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. Key cannot be repeated, val can be repeated, key will overwrite the original value
map.set('name'.'tom');
map.set('hob'.'sing');
console.log(map);   //Map(5) {"name" => "tom", "age" => 23, "hob" => "sing"}
Copy the code

The Map of traverse

  • Let of traverse the map
  • The forEach traverse map
  • Let of traverse the map. Keys
  • Let of iterate through map. Values
  • Let of iterate through map. Entries
  • Let of traverse map. Entries + deconstruct
// 1
    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's go through map
    for (let k of map.keys()) {
        console.log(k, map.get(k));
    }
    
    // 4. Let map. Values
    for (let v of map.values()) {
        console.log(v);
    }
    
    // 5. Let of iterate through map. Entries
    for (let i of map.entries()) {
        console.log(i[0], i[1]);
    }
    
    // 6. Let of iterate through map. Entries
    for (let [k, v] of map.entries()) {
        console.log(k, v);
    }
Copy the code

Es6 Set and Map type conversion

SetAnd an array1.Set -> array1. Array.from(); way2.Go through set and push3.Extended operator2.Array -> set1. new Set(arr);
    


MapObject string1.Map -> Object ->Stringway1.The forEach traversalMap- > object - >JSON.stringify
    2.String-> Object -> Map1. JSON.parse -> object ->for. In traversal object ->Map.add()
Copy the code

Between Set and array

let set = new Set(a); set.add(1).add(2).add(3).add(2);
// 1.Array.from();
var arr = Array.from(set);
console.log(arr);

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

// 3. Extend the operator
var arr = [...set];
console.log(arr);
Copy the code

Map, object, and string

let map = new Map(a); 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(a);for(let i in obj1){
    map1.set(i,obj1[i]);
}
console.log(map1);
Copy the code

Rest and extension operators

Rest parameters, appear in function parameter position discrete data -> array

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

⚠️** Note: **… The extension operator appears in the nonparametric position **

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);
Copy the code
  • Array -> Discrete data
  • NodeList HTMLCollection Arguments…

ES6 is object-oriented

classClass, template 1. constructor: Constructor 2 is automatically executed when a class is instantiated. Each class must have at least one constructor. If there is no constructor, the system automatically adds one without parameters. 3. Constructor, cannot be called activelysetgetSets and gets property 1.getParameter cannot be passed. 2setMethodgetStatic method: 1. Class own method, without instantiation can be called 2. Static attributes are not inherited by the instance. Static attributes are called directly from the class: 1. The property name= value;extendsImplementation inheritance1.Inheritance is one-way2.The inherited class belongs to the parent class, the base class, also known as the superclass3.Static methods can be inherited by subclasses4.Inherit the attributessuper() must be placed in the first constructor sentence5.A parent class can have multiple subclasses, and a subclass can have only one parent class note:1.A parent class can call its own member methods2.A parent class can call its own static methods3.A parent class cannot call a member method of a class4.Instances of subclasses can call superclass member methods5.Instances of subclasses cannot call superclass static methods6.Subclasses can call static methods of their parent classCopy the code
class Person {
  static name = "Ken";
  constructor(uname, uage) {
    this.uname = uname;
    this.uage = uage;
  }

  // Member methods
  walk() {
    console.log(`The ${this.uname}Running! `);
  }

  // Static methods: methods of the class itself
  static cry() {
    console.log('Man is born to cry! '); }}// Static attributes
Person.living = 'earth';


// The student class inherits 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 methods
  study() {
    console.log(`The ${this.sname}I'm learning! `);
  }

  // Set accessor controls the setting of properties
  set sage(age) { this._age=age}
  // get accessors to get attributes
  get sage() { return this._age }
}
// Create an instance of the class
var stu = new Student('Wang Sa'.23.'001');
stu.sage = 25
console.log(stu.sage);
Copy the code

Exception handling in JS

try..catch
try..finally
try...catch..finally
Copy the code

ES6 Promise solves callback hell

Promise: An instance that generates a promise to solve callback hell in asynchronous programming needs to accept a function as an argument that in turn accepts two functions as arguments: resolve, reject

Fullfilled successfully resolved successfully execute the resolve function rejected failed execute the reject function

The first parameter of then method is the implementation of resolve function. The second parameter is the implementation of reject function

The then method returns a new Promise instance ⚠️ Note that it is not the original Promise instance. If the previous callback returns a Promise object (i.e. an asynchronous operation), the later callback will wait for the state of the Promise object to change before it is called

Exception handling for promises

  1. Always use the catch method.
  2. Errors in the Promise object are “bubbling” and are passed backwards until they are caught.
  3. Once a Promise’s state changes, it stays that state forever.
  4. The catch method again returns a Promise object
  5. When catch and reject occur together, only reject is executed

Multiple asynchronous operations

// Load the 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(` Numbers for${id}The task failed);
        }
        // oImg.src = src;
        setTimeout(() = > {
            oImg.src = src;
        }, sec);   // Lazy loading function})}let s1 = "Remote picture";
let s2 = "Remote picture";
let p1 = loadPic('001', s1, 1000);
let p2 = loadPic('002', s2, 100);
/ / Promise. All methods
// Then is not executed when all images are loaded
let p = Promise.all([p1, p2]);  //all returns a new Promise object
p.then(data= >{
    console.log(data,'Load successful');
    document.body.append(data[0],data[1]);
}).catch(err= >{
    console.log(err);
}).finally(() = >{
    console.log('I'm going to do it whether I succeed or not.');
}); 
/ / Promise. Race method
/ / note:
// 1. Execute the resolve implementation of THEN as soon as one image is loaded
// 2. If the first image fails to be loaded, execute catch or reject
let p = Promise.race([p1, p2]);
p.then(data= > {
    console.log(data);      // only the first successful load is returned
    document.body.append(data);    // The second load completes first due to the delay set
}).catch(err= > {
    console.log(err);
})
Copy the code

ES module imports rules

Where things could go wrong

  1. The page does not run on a server basis and cross-domain errors occur
origin 'null' has been blocked by CORS policy: Cross origin requests are only
Copy the code
  1. When using modularity, pages without type = “module” will have syntax errors

app.js:1 Uncaught SyntaxError: Unexpected token {

<script src="./module/app.js" type="module"></script>
Copy the code
  1. If you do not add the.js suffix when importing a module, the module cannot be found

GET xxx net::ERR_ABORTED 404 (Not Found)

import { Student } from './Student.js';
Copy the code

Export way

  • Export at definition
  • The batch export
  • Export rename (not recommended)
  • The default is derived
// 1. Export when defining
export let uname = 'bill';

export function showStudentName() {
  console.log(uname);
}

export class SomeAnimalInfo {
  constructor(type, age) {
    this.type = type;
    this.age = age;
  }
  showInfo() {
    console.log(` species:The ${this.type}Age:The ${this.age}`); }}// 2. Batch export
const PI = 3.1415926;
const DBNAME = 'Local'; . .export { PI, DBNAME };



// 3. Default export - utility class
export default class {
  static log(msg) {
    let now = new Date(a);console.log(`${now.toLocaleString()}    ${msg}`);
  }

  static setCookie(){}... . }Copy the code

Import the way

  • Import renaming
  • Import the entire module
  • Import default modules
//1. Import the as renaming syntax
import { num, showStudentName as showName } from './all.js';

// 2. Import the entire module to be renamed using AS, which receives an object
import * as cons from './const.js';

// 3. Import the default module with a name that contains the exported content
import Tool from './tools.js';
Copy the code

Es7 grammar

Async await transforms es5

async function asyncFN() {
  var getSyncFnResult = await syncFn()
  console.log(getSyncFnResult);
}

function syncFn() {
  return "This is the result of syncFn()";
}

asyncFN()
Copy the code

After converting to ES5:

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
  try {
    var info = gen[key](arg); -fn['next'](" This is the result of syncFn() ")
    var value = info.value;
  } catch (error) {
    reject(error);
    return;
  }
  if (info.done) {
    resolve(value);
  } else {
    Promise.resolve(value).then(_next, _throw); }}function _asyncToGenerator(fn) {
  -fn=function* () {
  // var getSyncFnResult = yield syncFn();
  // console.log(getSyncFnResult);
  // }
  return function () {
    var self = this,
      args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);
      function _next(value) {
        console.log("value", value);

        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
      }
      function _throw(err) {
        asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
      }
      _next(undefined);
    });
  };
}

function asyncFN() {
  return _asyncFN.apply(this.arguments);
}

function _asyncFN() {
  _asyncFN = _asyncToGenerator(function* () {
    var getSyncFnResult = yield "This is the result of syncFn()";
    // var getSyncFnResult = yield syncFn();
    console.log(getSyncFnResult);
  });

  return _asyncFN.apply(this.arguments);
}

// function syncFn() {
// return "This is the result of syncFn() ";
// }

asyncFN();
Copy the code

reference