ES6-ES11
Author:gavin, this article is a personal note of Shang Silicon Valley ES learning
Video link
ES6
P2 - what is ES6?
P3 let variable naming and characteristics
- Declaration cannot be repeated
- Block level scope
- There is no variable promotion. It is useless to write before declaration
- It does not affect the action chain
P4 let exercise
P5 const declaration constants and features
- The initial value must be assigned
- General constants use uppercase
- Constant value cannot be modified (generally array, object)
- Block level scope
P6 deconstruction assignment
// 1. Array deconstruction const F4 = ["Xiao Ming", "Xiao Hong", "Xiao Liang", "Xiaobai"]; let [mk, hs, ll, bd] = F4; // 2. Object deconstruction const ming = { name: "Xiao Ming", age: "18", }; let { name, age } = ming;
P7 template string
// 1. Declaration let str = `I am string`; // 2. Line breaks can appear directly in the content let str = `<span>isString</span>`; // 3. Variable splicing let lovest = "Lau Andy"; let out = `${lovest}Is my idol`;
P8 object abbreviation method
let name = 'Xiao Ming', let age = 18, const person={ name, age, improve(){ console.log('I can work') } }
P9 arrow function and declaration
// statement let fn = function () {}; let fn = (a, b) => { return a + b; }; // call fn(a, b); // 1. this always points to the value of this under the scope // 2. It cannot be used as a method to construct an instance object let Person = (name, age) => { this.name = name; this.age = age; }; let me = new Person("xiaoming", 20); // 3. The arguments variable cannot be used let fn = () => { console.log(arguments); }; fn(1, 2, 3); // 4. Abbreviation of arrow function // The formal parameter is unique, and the parentheses can be omitted // In the code body, the curly braces are omitted. In this case, the return must be omitted, and the statement execution result is the return value let pow = (n) => n * n;
P10 application scenario of arrow function
// 1. Timer callback, using the scope this // 2. Return even elements from the array const arr = [1, 5, 6, 7, 652]; const result = arr.filter((item) => item % 2 === 0); console.log(result); // It is suitable for callbacks unrelated to this, timer and array methods // It is not suitable for callbacks related to this, event callbacks and object methods
P11 function parameter default value setting
// 1. Formal parameter initial value, parameter with default value, position depends on the back (hidden rule) add(a,b,c=10){ return a + b + c; } let result add(1,2); // 2. Combined with deconstruction assignment function connect({ host = "127.0.0.1", username, password, port }) { console.log(host); console.log(username); console.log(password); console.log(port); } connect({ username: "root", password: "root", port: 3306, });
P12- rest parameter
// ES5 get arguments function date() { console.log(arguments); } date("ming", "gavin", "lily"); // The rest parameter must be placed at the end of the parameter function date(a, b, ...args) { console.log(args); //array } date(1, 2, 3, 4, 5, 6);
Introduction and application of P13-P14 extension operator
The "..." extension operator can convert "array" into "parameter sequence"
// 1. Array merging const arr = [1, 2, 3, 4, 5]; const fh = ["gain", "pocket money"]; const he = [...arr, ...fh]; console.log(he); // 2. Array cloning const szh = ["E", "G"]; const syc = [...szh]; console.log(syc); //3. Convert pseudo array to real array const divs = document.querySelectorAll("div"); const divArr = [...divs]; console.log(divArr);
Introduction and creation of p15 symbol
The seventh type of js is used to resolve naming conflicts
// Create Symbol let s = Symbol(); let s2 = Symbol("gavin"); let s3 = Symbol("gavin"); console.log(s2 === s3); let s4 = Symbol.for("gavin"); console.log(s4, typeof s4); // Cannot be calculated with other data // let result = s + s; // USONB // u undefined // s String Symbol // o Object // n null Number // b Boolean
Application of p16 symbol
const game = { up() { console.log("up!"); }, down() { console.log("down"); }, }; // First: add a Symbol outside an object; let methods = { up: Symbol(), down: Symbol(), }; game[methods.up] = () => { console.log("Up To"); }; game[methods.down] = () => { console.log("Down to"); }; console.log("game object", game); // Second: internally defined Symbol let steam = { name: "Werewolf kill", [Symbol("say")]: () => { console.log("I can Say!"); }, [Symbol("run")]: () => { console.log("Run to world"); }, }; console.log("steam", steam);
Built in properties of p17 symbol (not commonly used)
P18-19 iterator introduction???
// Principle of iterator traversing objects const four = ["Tang Monk", "Sun WuKong", "Monk Sha"]; let iterator = four[Symbol.iterator](); // console.log(iterator.next()); // Declaration object const myclass = { name: "Class 11 of senior high school", studensts: ["ming", "ling", "stars"], [Symbol.iterator]() { // Index variable let index = 0; let _this = this; return { next: function () { if (index < _this.studensts.length) { const result = { value: _this.studensts[index], done: false }; // Subscript auto increment, return result index++; return result; } else { return { value: undefined, done: true }; } }, }; }, }; //Traverses the object and is a member of students for (let v of myclass) { console.log(v); }
P20 generator function declaration and call
// Generator is a special function // Asynchronous programming, pure callback function, node FS Ajax mongodb function* gen() { yield "A sheep"; yield "Two sheep"; yield "Three sheep"; } // let iterator = fen(); for (let v of gen()) { console.log(v); }
P21 parameter passing of generator function
function* gen(arg) { console.log(arg); let one = yield 111; console.log(one); let two = yield 222; console.log(two); let three = yield 333; console.log(three); } // Execute get iterator object let iterator = gen("AAA"); console.log(iterator.next()); // The next method can pass arguments console.log(iterator.next("BBB")); console.log(iterator.next("CCC")); console.log(iterator.next("DDD"));
P22-P23 generator function instance
//Asynchronous programming file operation network operation database operation // Requirements: output 111 after 1s, output 222 after 2s and output 333 after 3s // Callback hell setTimeout(() => { console.log(111); setTimeout(() => { console.log(222); setTimeout(() => { console.log(333); }, 3000); }, 2000); }, 1000); function one() { setTimeout(() => { console.log(111); iterator.next(); }, 1000); } function two() { setTimeout(() => { console.log(222); iterator.next(); }, 2000); } function three() { setTimeout(() => { console.log(333); iterator.next(); }, 3000); } function* gen() { yield one(); yield two(); yield three(); } //Second example function getUsers() { setTimeout(() => { let data = "user data"; iterator.next(data); }, 1000); } function getOrders() { setTimeout(() => { let data = "Order data"; iterator.next(data); }, 1000); } function getGoods() { setTimeout(() => { let data = "Commodity data"; iterator.next(data); }, 1000); } function* gen() { let user = yield getUsers(); console.log(user); let orders = yield getOrders(); console.log(orders); let goods = yield getGoods(); console.log(goods); } // Call generator function let iterator = gen(); iterator.next();
P24 promise introduction and basic use
const p = new Promise(function (resolve, reject) { setTimeout(() => { // let data = "data in database"; // resolve(data); let err = "Data reading failed"; reject(err); }, 1000); }); p.then( function (value) { console.log(value); }, function (reason) { console.log(reason); } );
P25 promise package read file
const fs = require("fs"); const p = new Promise(function (resolve, reject) { fs.readFile("./es6 study.md", (err, data) => { // Judgment failure if (err) reject(err); // success resolve(data); }); }); p.then( (value) => { console.log(value.toString()); }, (err) => { console.log("Failed!!!", err); } );
P26 promise encapsulates AJAX requests
const p = new Promise((resolve, reject) => { // create object const xhr = new XMLHttpRequest(); // initialization xhr.open( "GET", "http://rap2api.taobao.org/app/mock/293221/manage/category/info" ); // send out xhr.send(); // Binding event xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr.response); } else { reject(xhr.status); } } }; }); // Specify callback p.then( function (value) { console.log(value); }, (reason) => { console.log(reason); } );
P27-Promise.prototype.then method
// Create Promise object const p = new Promise(function (resolve, reject) { setTimeout(() => { let data = "Data in database"; resolve(data); // let err = "data reading failed"; // reject(err); }, 1000); }); // Call the then method. The return result of the then method is the Promise object, and the object state is determined by the execution result of the callback function // 1. The returned result is a non promise attribute, the status is success, and the returned value is the object success value. // call chaining p.then(function (value) { console.log(value); }).then((result) => { console.log(result); });
28 promise practical exercise - reading the contents of multiple files
import fs = require('fs') fs.readFile("./resources/one.md", (err, data) => {}); const p =new Promise((resolve,reject) => { fs.readFile('./one.md'),(err,data) => { resolve(data); } }) p .then((value) => { return new Promise((resolve,reject) => { fs.readFile('./two.md',(err,data) => { resolve([value,data]) }) }) }).then((value) => { return new Promise((resolve,reject) => { fs.readFile('./three.md',(err,data) => { value.push(data); resolve(value) }) }) }).then((value) => { console.log(value) })
catch method of P29 promise
const p = new Promise((resolve, reject) => { setTimeout(() => { reject("err"); }, 1000); }); p.then((result) => { console.log(result); }).catch((err) => { console.log(err); });
P30 - set introduction and API
// Declare a set let s = new Set(); let s2 = new Set(["123", "456", "789", "123"]); // Number of elements console.log(s2.size); // Add new element s2.add("000"); // Delete element s2.delete("111"); // testing console.log(s2.has("789")); // empty s2.clear(s2); console.log(s2); // forof traversal for (let v of s2) { console.log(v); }
P31 collective practice
let arr = [1, 2, 3, 4, 5, 6, 7, 1, 2, 3]; // Array de duplication let result = [...new Set(arr)]; console.log(result); // intersection let arr2 = [4, 5, 6, 7]; // result = result.filter((item) => { // let s2 = new Set(arr2); // if (s2.has(item)) { // return true; // } else { // return false; // } // }); result = [...new Set(arr)].filter((item) => new Set(arr2).has(item)); console.log(result); // Union let union = [...new Set([...arr, ...arr2])]; console.log(union); // Difference set let diff = [...new Set(arr)].filter((item) => !new Set(arr2).has(item)); console.log(diff);
Introduction and API of P32 map
// Declare Map let m = new Map(); // Add element m.set("name", "gavin"); m.set("change", () => { console.log("We can change!"); }); let key = { school: "SCHOOL", }; m.set(key, ["Beijing", "Shanghai", "Guangzhou"]); // size console.log(m.size); // delete m.delete("name"); // obtain console.log(m.get("change")); console.log(m.get(key)); // empty m.clear(); // ergodic for (const v of m) { console.log(v); }
P33 class understanding
// ES5 function factory function Phone(brand, price) { this.brand = brand; this.price = price; } Phone.prototype.call = function () { console.log("I can call!"); }; // Instantiate object let Huawei = new Phone("Huawei", 666); Huawei.call(); console.log(Huawei); // Class ES6 class shouji { // Construction method constructor(brand, price) { this.brand = brand; this.price = price; } call() { "I can Call you!"; } } let oppo = new shouji("oppo", 9999); console.log(oppo);
P34 class static member
// ES5 function Phone() {} (Phone.name = "mobile phone"), (Phone.change = function () { console.log("I can change the world"); }); Phone.prototype.size = "5 foot"; let nokia = new Phone(); console.log(nokia.name); console.log(nokia.size); // ES6 class Phone { // Static member static name = "Notes"; static change() { console.log("you cab change world!"); } } let nokia = new Phone(); console.log(nokia.name); console.log(Phone.name);
P35-ES5 constructor inheritance
// mobile phone function Phone(brand, price) { this.brand = brand; this.price = price; } Phone.prototype.call = function () { console.log("I can Call you!"); }; // Intelligent mobile phone function SmartPhone(brand, price, color, size) { Phone.call(this, brand, price); this.color = color; this.size = size; } // Prototype constructor SmartPhone.prototype = new Phone(); SmartPhone.prototype.constructor = SmartPhone; // Declare subclass methods SmartPhone.prototype.playGame = function () { console.log("I can play games"); }; const oppo = new SmartPhone("OPPO", 1234, "White", "6inch"); console.log(oppo);
P36 class inherits P37 subclass's override of parent class method
class Phone { constructor(brand, price) { this.brand = brand; this.price = price; } call() { console.log("I can call"); } } class SmartPhone extends Phone { constructor(brand, price, color, size) { super(brand, price); this.color = color; this.size = size; } photo() { console.log("I can take pictures!"); } playGame() { console.log("I can play games"); } call() { console.log("I can make video calls!!!"); } } const xiaomi = new SmartPhone("millet", 1221, "Pink", "6 inch"); console.log(xiaomi); xiaomi.call(); xiaomi.photo(); xiaomi.playGame();
P38 setting of getter and setter
class Phone { get price() { console.log("The price attribute is read"); return "isme"; } get price() { console.log("Price attribute modified"); } } let s = new Phone(); console.log(s); s.price = "free";
Numerical extension of P39-40-ES6 & & object method extension
// Object.assign object merge const config1 = { host: "localhost3000", prot: 3306, name: "root", test: "2", }; const config2 = { host: "localhost5000", prot: 3307, name: "gavin", }; console.log(Object.assign(config1, config2)); // {host: 'localhost5000', prot: 3307, nam: 'gavin'}
P41-P42-P43-P44-modular
Modular specifications before ES6 include:
- CommonJS => NodeJS,Browserify
- AMD => requireJS
- CMD => seaJS
The module function is mainly composed of two commands: export and import.
- The export command is used to specify the external interface of the module
- The import command is used to input functions provided by other modules
// 1. General import method import * as m1 from "./a.js"; // 2. Deconstruction of assignment form import { school, teacher } from "./a.js"; import { school as guigu, teacher } from "./a.js"; // 3. Simple form (for default exposure) import A from "./a.js";
P45 - another way for browsers to use ES6
P46 Babel to ES6 modular code conversion
- Installation tool Babel cli Babel preset env browerify (webpack)
- Translate npx babel src/js -d dist/js
- Package npx browserify dist/js/app.js -o dist/bundle.js
P47-ES6 modular introduction of NPM package
P48-ES7 new features
- includes determines whether the array contains an element
- 2 * * 10 (the 10th power of 2)
P49-ES8 async function
async function fn() { // 1. Return a string // return "Silicon Valley"; // As long as reject is not called back, the Promise object is successful // return; // 2. Throw an error and return a failed Promise object // return new Error("error"); // 3. The returned result is Promise object return new Promise((resolve, reject) => { // resolve("success"); reject("fail"); }); } const result = fn(); console.log(result); // Call the then method result.then( (value) => { console.log(value); }, (err) => { console.warn(err); } );
P50-P51-ES8-async and await read file contents
function study() { fs.readFile("../es6 study.md", (err, data) => { if (err) reject(err); resolve(data); }); } async function main() { let study = await study(); console.log(study.toString()); } main();
P52 async sends a request in combination with await
Write asynchronous requests in a synchronous way. await can receive specific values after waiting. It is not a Promise object
// Request encapsulation function sendAJAX() { return new Promise((resolve, reject) => { // 1. Create object const x = new XMLHttpRequest(); // 2. Initialization x.open("GET", url); // 3. Send x.send(); // 4. Event binding x.onreadystatechange = function () { if (x.readyState === 4) { if (x.status >= 200 && x.status < 300) { resolve(x.response); } else { reject(x.status); } } }; }); } // promise then method test // sendAJAX("http://rap2api.taobao.org/app/mock/293221/manage/user/add") // .then((value) => { // console.log(value); // }) // .catch((err) => { // console.log(err); // }); // async and await testing async function main() { let result = await sendAJAX( "http://rap2api.taobao.org/app/mock/293221/manage/user/add" ); console.log(result); }
P53-ES8 object method extension
const school = { name: "silicon valley", subject: ["web", "JAVA", "big data"], }; // Get all keys of the object console.log(Object.keys(school)); // Get all values of the object console.log(Object.values(school)); // Get entries object console.log(Object.entries(school)); // ★ it is mostly used to create maps const m = new Map(Object.entries(school)); console.log(m); // Create a description object for the attribute console.log(Object.getOwnPropertyDescriptors(school));
P54-ES9 extension operator and rest parameter
// ES9 provides the same rest parameters and extension operators for objects as arrays function connect({ host, port, ...user }) { console.log(host), console.log(port), console.log(user); } connect({ host: "localhost", port: "3306", username: "gavin", password: "12345", }); const skillOne = { q: "having dinner", }; const skillTwo = { w: "sleep", e: "Play games", }; const gavin = { ...skillOne, ...skillTwo }; console.log(gavin);
P55-ES9 regular extension - named capture packet
Collect and name regular data
// Declaration string let str = "<a href='www.bilibili.com'>b station</a>"; // Extract url and [label text] // const reg = /<a href='(.*)'>(.*)<\/a>/; // Named capture group const reg = /<a href='(?<url>.*)'>(?<text>.*)<\/a>/; // implement const result = reg.exec(str); console.log(result); // console.log(result[1]); // console.log(result[2]); console.log(result.groups.url); console.log(result.groups.text);
P56-ES9 regular extension - reverse assertion
Match from back to front
// Declaration string let str = "JS12345 You know, 555 Lala"; // Forward assertion // const reg = /\d + (? = LA) /; // const result = reg.exec(str); // Reverse assertion const reg = /(?<=Do you)\d+/; const result = reg.exec(str); console.log(result);
P57-ES9 regular extension dotAll mode
Replace newline
// dot. Metacharacter representing any single character other than the newline character let str = ` <ul> <li> <a>The Shawshank Redemption </a> <p>Date: 1998-1-1</p> </li> <li> <a>Forrest Gump</a> <p>Date: 1998-1-1</p> </li> </ul>`; // Declarative regularity // const reg = /<li>\s+<a>(.*?)<\/a>\s+<p>(.*?)<\/p>/; const reg = /<li>.*?<a>(?<title>.*?)<\/a>.*?<p>(?<time>.*?)<\/p>/gs; // Perform matching // const result = reg.exec(str); // console.log(result); let result; let data = []; while ((result = reg.exec(str))) { data.push({ title: result.groups.title, time: result.groups.time }); } // Output results console.log(data);
P58-ES10 object extension method Object.fromEntries
Turn a 2D array into an object
// Two dimensional array variable object // const result = Object.fromEntries([ // ["name", "gavin"], // ["object", "Java, big data, front end"], // ]); // console.log(result); // Map // const m = new Map(); // m.set("name", "GVIGU"); // const result = Object.fromEntries(m); // console.log(result); // Object.entries ES8 object variable array const school = { name: "Shang Silicon Valley", Object: "java", }; const arr = Object.entries(school); console.log(arr);
P59-ES10-string method extension
trim clear space
let str = " i am gavin "; console.log(str); console.log(str.trim()); console.log(str.trimStart()); console.log(str.trimEnd());
P60-ES10 array method extends flat and flatMap
Flatten and shell the array
// The flat parameter is the depth and is a number // const arr = [1, 2, 3, [4, 5, 6, [7, 8, 9]]]; // console.log(arr.flat(1)); // flatMap is equivalent to Map before flat const arr = [1, 2, 3, 4, 5, 6]; const result = arr.flatMap((item) => [item * 10]); console.log(result);
P61 - create description of Symbol
Create Symbol description
// Create Symbol let s = Symbol("Shang Silicon Valley"); console.log(s.description);
P62-ES11-class private attribute
class Person { name; // Private property #age; #weight; constructor(name, age, weight) { this.name = name; this.#age = age; this.#weight = weight; } intro() { console.log(this.#age); console.log(this.#weight); } } const girl = new Person("Little green", 12, "50kg"); console.log(girl); // console.log(girl.#age); girl.intro();
P63-ES11-Promise.allSettled method
// Declare two promise s const p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve("less than p1"); }, 1000); }); const p2 = new Promise((resolve, reject) => { setTimeout(() => { // resolve("p2 missing"); reject("error"); }, 1000); }); // Call the allSettled method to return the detailed Promise object const result = Promise.allSettled([p1, p2]); console.log(result); // All returns only after all are successful const res = Promise.all([p1, p2]); console.log(res);
P64-ES11-String.matchAll
★ very practical, used to get regular batch matching results
let str = ` <ul> <li> <a>The Shawshank Redemption </a> <p>Date: 1998-1-1</p> </li> <li> <a>Forrest Gump</a> <p>Date: 1965-1-1</p> </li> </ul> `; const reg = /<li>.*?<a>(?<title>.*?)<\/a>.*?<p>(?<time>.*?)<\/p>/gs; const result = str.matchAll(reg); // console.log(result); // for (let v of result) { // console.log(v); // } const arr = [...result]; console.log(arr);
P65-ES11-optional chain operator
★ practical and can be used to simplify judgment
// ?. function main(config) { // const dbHost = config && config.db && config.db.host; const dbHost = config?.db?.host; console.log(dbHost); } main({ db: { host: "localhost:3000", username: "root", }, });
P66-ES11-dynamic import
Dynamic introduction, lazy loading
// The return value is promise object, which is loaded lazily import("./hello.js").then((module) => { module.hello(); });
P67-ES11-BigInt type
Used for very large numerical operations
// Large numerical operation let max = Number.MAX_SAFE_INTEGER; console.log(max); console.log(max + 1); console.log(max + 2); console.log(BigInt(max)); console.log(BigInt(max) + BigInt(1)); console.log(BigInt(max) + BigInt(2));
P68 - absolute global object globalThis
Always point to global objects