ES6+ - Learning Summary

1. Changes in focus

  • Solve some problems or deficiencies in the original grammar
  • Enhancements to the original grammar
  • New objects, new methods, new features
  • Brand new data types and data structures

2.let and block scope

  • A block-level scope is simply a code segment enclosed in "{}" or parentheses, and cannot be called outside a variable declared with let in a block-level scope.
  • Variables declared with let do not generate variable hoisting

3. Array destructuring

//Assign by position
const arr = [100, 200, 300];
const [foo, bar, baz] = arr;
console.log(foo);

//...assign the rest of the value to rest, which can only be used at the end of the destructuring position
const [f, ...rest] = arr;

//object destructuring
const obj = {name: 'lin', age: 12};
const { name } = obj;
const { name: objName } = obj;  //Rename

4. Template strings

  • literal
const name = "lin";
const str = `my name is ${name}`;
console.log(str);
  • Label function to process template strings
const name = "lin";
const gender = true;

function myTagF(string, name, gender){
    // const sex = gender ? 'man' : 'woman';
    // return string[0] + name + string[1] + sex + string[2];
    
    return string[0] + name + string[1] + gender + string[2];
}
//Parse the template string to return an array ['hey,', ' is a ', '.'];
const result = myTagF`hey,${name} is a ${gender}.`;
//Returns hey,lin is a true.
console.log(result);

5. String extension methods

  • includes()
    • Determine whether a string contains a certain value, which is convenient for string search
  • startsWith()
    • Check if a string starts with a certain value
  • endsWith()
    • Check if the end of a string contains a certain value
let msg = 'this is a message';
console.log(msg.includes('o'));  // false
console.log(msg.startsWith('t'));  // true
console.log(msg.endsWith('t'));  // false

6. Function expansion syntax

  • The default value of the parameter. If no actual parameter is passed, or the actual parameter is undefined, the default value of the formal parameter is used; if there are multiple formal parameters with default values, the formal parameters should be placed at the end.
  • ...rest, accepts all actual parameters in the form of an array, and puts them in the last place in the form of formal parameters, which can only be used once
  • Spread operator …
// parameter default value
function fun1(a = 100){
    console.log(a)
}

// ...rest remaining parameters
function fun2(...args){
    console.log(args)
}
fun2(1,2,3,4,5)

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

7. Arrow functions

  • There is no this, it will not change the this point, it always points to this in the current scope, and new cannot be added to the arrow function, that is to say, the arrow function cannot be used as a constructor.
const a = (v, a) => v+a;

8. Object literal enhancements

const obj = {
    name: "lin",
    bar,    //The key and the value can omit the value
    method(){   //function
        console.log(this.name);
    },
    [2+3]: 1000,    //Computed property name
}

9.object.assign

  • Overwrite the same properties of the first variable with the properties of the second variable and merge the other properties into the second object
  • shallow copy
//property override
let obj1 = {
    a: 123,
    b: 123
}

let obj2 = {
    b: 456,
    c: 456
}

let result = Object.assign(obj1, obj2)
console.log(result)
console.log(result === obj1)    //The new object is equal to the first object

// shallow copy
let result = Object.assign({}, obj2)

10.object.is

  • Used to determine whether two values ​​are equal
console.log(Object.is(1, 2))

11.Proxy (data access proxy)

  • Ability to monitor many object operations
  • Monitoring of array objects, overriding operation methods of arrays
  • Supervises the reading and writing of objects in a non-intrusive way
const person = {
    name: 'lin',
    age: 20
}

const personProxy = new Proxy(person, {
    get(target, property){  //Get the properties of the object target object itself, property lookup properties
        console.log(target, property);
        return property in target ? target[property] : 'undefined';
    },
    set(target, property, value){   //Add an object attribute target object itself, the attribute added by property, the value corresponding to the value attribute
        if(property === 'age'){
            if(!Number.isInteger(value)){
                throw new TypeError(`${value} is not number`);
            }
        }

        target[property] = value;
        console.log(target, property, value);
    }
})

personProxy.like = 'JavaScript';

console.log(personProxy.name);

12.Reflect

  • Unified object operation api, which belongs to static class and cannot be constructed by new
  • Internally encapsulates a series of low-level operations on objects
  • The Reflect member method is the default implementation of the Proxy processing object
const person = {
    name: 'lin',
    age: 20
}

const personProxy = new Proxy(person, {
    get(target, property){ 
        console.log(target, property);
        return Reflect.get(target, property);
    }
})
console.log(personProxy.name);

// Unified object manipulation api
const obj = {
    name: 'lin',
    age: 20,
    like: 'JavaScript'
}
console.log(Reflect.has(obj, 'name'))   //Check if an object has a property
console.log(Reflect.deleteProperty(obj, 'like'))    //delete an attribute

13.Promise

  • Solve the callback hell of traditional asynchronous calls
  • The then method of the promise object returns a brand new promise object
  • The next then method is to register a callback for the promise object returned by the previous then
  • The return value of the callback function in the previous then method will be used as the parameter of the callback of the subsequent then method
  • If the callback returns a promise, then the callback of the then method will wait for its result
  • In general, the then chain call is actually calling the object of the promise returned by the previous then to add a callback after the state is clear. These promises will be executed sequentially from front to back.
  • method

    • promise.resolve()
      • Call back the successful promise object
    • promise.reject()
      • Callback failed promise object
    • parallel execution
      • promise.all()
        • Call all promise objects and return a new promise object, the callback result of receiving all objects with then will be placed in an array
        • Wait for all tasks to complete before returning the callback result
      • promise.rece
        • The same as promise, the difference is that it will only wait for the end of the first task
  • Basic usage

const promise = new Promise(function(resolve, reject){
    // resolve(100); //successful callback
    reject(new Error("promise reject error"));  //failure callback
})

promise.then(function(value){
    console.log(`resolve: ${value}`);
}, function(error){
    console.log(`reject: ${error}`);
})
  • Use case: wrapping ajax
function ajax(url){
    return new Promise(function(resolve, reject){
        let xhr = new XMLHttpRequest();
        xhr.open('get', url);
        xhr.responseType = 'json';
        xhr.onload = function(){
            if(xhr.status === 200){
                resolve(this.response);
            }else{
                reject(new Error(this.statusText));
            }
        }
        xhr.send();
    })
}

ajax('./user.json')
.then(function onFulfilled(res){
    console.log(res);
}, function noRejected(error){
    console.log(error);
})

//or
ajax('./user.json')
.then(function onFulfilled(res){
    console.log(res);
})
.catch(function noRejected(error){
    console.log(error);
})

14.class class

  • Classes can be inherited using extends
  • Static methods add the keyword static before the method
  • Use super to access members of parent class
class Person {
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    sayHi(msg){
        console.log(`name: ${this.name}, age: ${this.age}, ${msg}`);
    }
}

class Student extends Person{
    constructor(name, age){
        super(name, age);
    }
    static create(name, age){   //static method
        return new Student(name, age);
    }
}

const tom = new Person('TOM', 20);
tom.sayHi("hello ");
console.log(tom.name);

const jack = Student.create('jack', 10);
jack.sayHi("hello ");

15.Set

  • unique set
  • The size() method gets the set length
  • The has() method indicates whether a value is contained and returns true or false
  • The delete() method means to delete an item of data and returns true or false
  • clear() method means to clear the collection
//Array deduplication
let arr1 = [1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6];
let arr2 = [...new Set(arr1)];
console.log(arr1);
console.log(arr2);

16.Map

  • object-like data
  • A map can use any type as a key, while an object's keys can only be strings
let m = new Map();
let obj = {
    name: 'lin',
    age: 20
};
m.set(obj, 90);
console.log(m);

17.Symbol

  • The main function is to add a unique property name to the object
  • Can be used as a private property of an object
  • Object properties of type symbol can be obtained with Object.getOwnPropertySymbols(obj)
let obj = {
    name: 'lin',
    age: 20,
    [Symbol(123)]: '123'
};
console.log(obj);
// Get the attribute name of the symbol type
console.log(Object.getOwnPropertySymbols(obj));

18.for-of loop

  • as a unified way to traverse all data structures
  • A loop can be terminated with break
  • The method of Symbol.iterator must be implemented. Symbol.iterator must contain the object of the next() method. Continuously calling the next method can traverse all the internal data.
  • Implement iterable interface
const obj = {
    store: ['foo', 'bar', 'baz'],
    [Symbol.iterator]: function() {     //Implementing the iterable interface iterable must have an iterator method that returns an iterator
        let index = 0;
        const self = this;

        return {    //Implementing the iterator interface iterator must have a next method inside it for iteration
            next: function() {
                const result = {
                    value: self.store[index],   //data for the current iteration
                    done: index >= self.store.length    //Implement the iteration result interface iterationResult indicates whether the iteration is over, true means no, false means it still exists
                }
                index++;
                return result;
            }
        }
    }
}

for (const item of obj){
    console.log("loop body", item);
}
//loop body foo
//loop body bar
//loop body baz
  • iterator pattern
    • Provide a unified interface to the outside, regardless of the internal structure
const todos = {
    store: ['foo', 'bar', 'baz'],
    life: ['Have a meal', 'sleep', 'watch anime'],
    learn: ['JavaScript', 'java', 'node'],

    each: function(callback){   //Provide a unified traversal interface to the outside world
        const all = [].concat(this.store, this.life, this.learn);
        for (const item of all){
            callback(item);
        }
    },

    [Symbol.iterator]: function() {  //Custom iterable interface (iterator)
        let index = 0;
        const all = [...this.store, ...this.life, ...this.learn];

        return {
            next: function() {
                const result = {
                    value: all[index],
                    done: index >= all.length
                }
                index++;
                return result;
            }
        }
    }
}

//common method
todos.each(function(item){
    console.log(item);
})

console.log("++++++++++++++++++++++++++++");

//iterator method
for (const item of todos){
    console.log(item);
}

19. Generator Generator

  • Add a * in front of a normal function to turn it into a generator function
  • Avoid deep nesting of callbacks in asynchronous programming and provide better asynchronous programming solutions
  • A generator object is automatically returned, and the function body of the next method of this object is called to start execution. When encountering the yield keyword, the function will be suspended. The value after yield will be returned as the return result of next. If you continue to call next, it will be executed from the paused position. , until the function body completely ends
function * foo() {
    console.log("111");
    yield 100;
    console.log("222");
    yield 200;
    console.log("333");
    yield 100;
}

const generator = foo();

console.log(generator.next());
// 111
// { value: 100, done: false }

console.log(generator.next());
// 222
// { value: 200, done: false }

console.log(generator.next());
// 333
// { value: 100, done: false }

console.log(generator.next());
// { value: undefined, done: true }
  • Generator App: Number Maker
function * createId() {
   let id = 1;
   while (true){
       yield id++;
   }
}

const id = createId();

console.log(id.next().value);
  • Implement the iterator method of the object
const todos = {
    store: ['foo', 'bar', 'baz'],
    life: ['Have a meal', 'sleep', 'watch anime'],
    learn: ['JavaScript', 'java', 'node'],
    [Symbol.iterator]: function * () {
        const all = [...this.store, ...this.life, ...this.learn];
        for (const item of all){
            yield item
        }
    }
}

for (const item of todos){
    console.log(item);
}

20. Modular Modules

  • Standard implementation of ES Modules can be achieved by adding the type="module" attribute to the script tag

  • characteristic:

    • ES Modules automatically use strict mode, ignoring "use strict"
    • Each ES Modules module runs in a separate private scope
    • ES Modules requests external JS modules through CORS
    • The script tag of ES Modules delays the execution of scripts
  • Export:

    const foo = 'ES Modules'
    const bar = 'bar'
    export { foo }
    // Export by default
    export default { foo }
    // Rename
    

    export {
    foo as fooName,
    bar as barName
    }

  • import:

    import { foo } from './module.js'
    console.log(foo)
    

    21.async-await

    • Essentially syntactic sugar for promise s
    • The statement after await requires a promise
    let a = 0;
    let b = async () => {
        a = a + await 10;
        console.log('2', a) ;// -> '2' 10
        a = (await 10) + a;
        console.log('3', a); // -> '3' 20
    };
    b();
    a++;
    console.log('1', a) ;// -> '1' 1
    

ECMAScript2016

1. New content

  • The include method of the array determines whether the array contains the specified element and returns a boolean value
  • Exponential operator for numbers 2**10

ECMAScript2017

1. New content

  • object object method

    • The value() method returns an array of all the values ​​in the object
    • The entries() method returns all key-value pairs in the object in the form of an array, so you can use for-of to traverse the object
    • getOwnPropertyDescriptors() method, get the complete description information of object properties
  • String padding, can be used as a string to output it

    • String.prototype.padStart
    • String.prototype.padEnd
  • Add trailing comma in function parameter

Tags: Javascript ECMAScript Front-end

Posted by Sweeney on Mon, 30 May 2022 09:42:03 +0530