Six new features that ES6 must know

Keywords: Javascript node.js Front-end ElasticSearch Vue.js

ES6

New features of ES6 let & const

  • const is used to represent constants (it is not allowed to change after declaration. Once declared, it must be initialized, otherwise an error will be reported)

//ES6 constant cannot be modified
	const b=2;
	b=3;//Uncaught TypeError: Assignment to constant variable.
	console.log(b);
  • Variables declared with var tend to cross the scope, while variables declared with let have strict local scope

// ES6
        // Variables declared by var tend to cross domain
        // let declared variables have strict local scope
        {
            var a=1;
            let c=3;
        }
        console.log(a);
        console.log(c);//Uncaught ReferenceError: c is not defined
  • let can only be declared once, and var can be declared multiple times

//var can be declared multiple times and let can only be declared once
        var a=1
        var a=3
        let b=2
        let b=4
        console.log(a)
        console.log(b)//Uncaught SyntaxError: Identifier 'b' has already been declared
  • let does not promote variables. Variable promotion means that variables can be used first and then declared

// var variable promotion
// let does not promote variables
        console.log(a)
        var a =1
        console.log(b)
        let b =2

What's new in ES6 - deconstruction & String

  • Deconstruction of array:

//Deconstruction of data
        let arr=[1,2,3];
        let a=arr[0];
        let b=arr[1];
        let c=arr[2];
        console.info(a,b,c);

//ES6: array deconstruction expression
        let[aa,bb,cc]=arr;
        console.info(aa,bb,cc);
  • Deconstruction of objects:

let person={
            name:'Xu Shu',
            age:11,
            hobbies:['sing','dance']
        }
        let name=person.name;
        console.info(name)

//ES6: Deconstruction expression of object
        let{name,age,hobbies}=person;
        console.info(name,age,hobbies);

  • String template: directly put html in ` `

let html="<div>"+"<a>Hello</a>"+"</div>";

//ES6: String template
let esHtml=`<div><a>Hello</a></div>`;
console.info(esHtml);
  • String extension:

//String extension
let str="hello.vue";
console.log(str.startsWith("hello"))//true
console.log(str.endsWith(".vue"))//true
console.log(str.includes("e"))//true
console.log(str.includes("hello"))//true
  • String inserts variables and expressions. Variable names can be written in , {}, , {} can put js expressions

 let person={
            name:'Xu Shu',
            age:11,
            hobbies:['sing','dance']
        }

        let{name,age,hobbies}=person;

        function fun(){
            return "This is a function"
        }
        //ES6: insert variables and expressions into strings. The variable name is written in ${}, ${}, which can be put into js expressions
        console.info(`The name is ${name},Age is ${age},Hobbies are ${hobbies},The return value of this function is ${fun()}`);

New feature of ES6 - function optimization

  • Function parameter default value: set the default value directly in parentheses

//1. The parameter default value of the function is before ES
        function add(a){
            if(!a){
                a=1;
            }
            console.log(a);
        }
        add();

//ES6: parameter default value of function
        function add(a=1){
            console.info(a);
        }
        add();
  • Variable length parameter: add before the parameter in parentheses

//2. Before variable length parameter ES
        function add(a){
            console.info(a);
        }
        add([1,2]);

//ES6: variable length parameter
        function add(...a){
            console.log(a);
        }
        add(1,2,3);

  • Parametric deconstruction

//ES6: parameter deconstruction
let nums={
            a:1,
            b:2
        }
        function add({a,b}){
            console.log(a+b);
        }
        add(nums);
  • Arrow function: it is more concise when one line is used. return is not required. It is required when multiple lines are used.

//Arrow function lambda = > before ES6
        function add(a,b){
             return a+b;
        }
        console.info(add(1,2));

//ES6: arrow function
        let add=(a,b)=>{
            let c=a+b
            console.log(c);
        }
        add(2,2);

ES6 new feature - object optimization

  • Built in function of object

    • keys() displays the properties of the object
    • values() displays the value of the property
    • entries() displays the properties and values of the object
    • Object merge function assign()
      • Note: the first parameter is the object to be merged, and other parameters will be merged on the first parameter (if there is the same successor)
// 1. Built in function of object
     let person = {
            name: "jack",
            age: 21,
            language: ['java', 'js', 'css']
        }

        console.log(Object.keys(person));//["name", "age", "language"]
        console.log(Object.values(person));//["jack", 21, Array(3)]
        console.log(Object.entries(person));//[Array(2), Array(2), Array(2)]


         // Object merge
         const target = { a: 1 };
        const source1 = { b: 2 };
        const source2 = { a:4,c: 3 };

        // Parameter description the first parameter is the object to be merged, and other parameters will be merged onto the first parameter
        // If there are duplicate attributes, they will be overwritten with the following ones
        Object.assign(target, source1, source2);

        console.log(target);//{a:4,b:2,c:3}
  • Declaration object abbreviation

    • Abbreviation of object attribute: if the attribute name is the same as the referenced variable name, the assignment can be omitted

      let name="Xu Shu";
      let age=11;
      
      // Before ES6
      let person={
           name:name,
           age:age
      }
      
      // ES6: abbreviation of object declaration attribute: if the attribute name is the same as the referenced variable name, the assignment can be omitted, and it will automatically call the variable with the same name
      let person={
          name,
          age
      } 
      console.info(person)
      
    • Abbreviation of the function in the object: use the arrow function declaration. If you want to call the property this of the object, it will become invalid. You need to use the method of object. Property

      // ES: shorthand for functions in objects
      let person={
          name:"Xu Shu",
      // Before ES6
          eat: function(food){
              console.info(this.name+"Eat:"+food)
          },
      // ES6: declared through the arrow function, if you want to call the attribute this of this object to point to window, you need to use the object. Attribute
          eat2: (food) => console.info(person.name+"Eat:"+food),
      //The third way is not to write colons
          eat3(food){
              console.info(this.name+"Eat:"+food)
          }
      }
      person.eat("rice");
      person.eat2("seafood");
      person.eat3("Fruits");
      
    • Object extension operators: copy and merge (...)

      //Object's extension operator
          //1. Copy object (deep copy)
          let person={name:"xushu",age:18,wife:{name:"Yang Di"}};
          let person2={...person};
          console.info(person2);
      
          //2. Consolidation object
          const target = { a: 1 };
          const source1 = { b: 2 };
          const source2 = { c: 3 };
          let newObject={...target,... source1,...source2};
          console.info(newObject);
      

New feature of ES6 - promise asynchronous orchestration

  • ajax request mode before ES:

    //Use functions to simplify, but still nested
    function myAjax(url, callback){
            $.ajax({
                url: url, 
                success: function (result) {
                    callback(result);
                }
            });
        }
    myAjax("http://localhost:8811/user/existUsername",function(result){
            if(result.data){
                				   myAjax("http://localhost:8811/user/existPhone",function(result){
                    
                })
            }
        })
    
    //Traditional ajax request mode
        Does the user name exist   
        $.ajax({
            url: "http://localhost:8811/user/existUsername",
            success: function (result) {
                if (result.data) {
                    alert('User name does not exist!')
                    // Does the phone exist
                    $.ajax({
                        url: "http://localhost:8811/user/existPhone",
                        success: function (result) {
                            if (result.data) {
                                alert('Mobile phone does not exist!')
                                // Registered user
                                $.ajax({
                                url:"http://localhost:8811/user/registryUser",
                                    success: function (result) {
                                        if (result.data) {
                                            alert(result.message)
                                        }
                                    },
                                    error: function (err) {
                                        alert("abnormal" + err)
                                    }
                                })
                            } else {
                                // Phone number already exists
                                alert(result.message)
                            }
                        },
                        error: function (err) {
                            alert("abnormal" + err)
                        }
                    })
                } else {
                    // User name already exists
                    alert(result.message)
                }
            },
            error: function (err) {
                alert("abnormal" + err)
            }
        })
    
    
  • promise asynchronous Orchestration:

    • When the resolve function is executed, it will call. then() to determine the result
    • When the reject function is executed, it will call. catch() to determine err
    new Promise((resolve, reject) => {
                // 1. Does the requested user name exist
                $.ajax({
                    url: "http://localhost:8811/user/existUsername",
                    success: function (result) {
                        resolve(result);
                    },
                    error: function (err) {
                        reject(err);
                    }
                })
            })
            // 2. Does the mobile phone exist
            .then(result => {
                return new Promise((resolve, reject) => {
                    if (result.data) {
                        alert('User name does not exist!')
                        $.ajax({
                            url: "http://localhost:8811/user/existPhone",
                            success: function (result) {
                                resolve(result);
                            },
                            error: function (err) {
                                reject(err);
                            }
                        })
                    } else {
                        alert(result.message)
                    }
                })
    
            })
            .then(result => {
                return new Promise((resolve, reject) => {
                    if (result.data) {
                        alert('Mobile phone does not exist!')
                        // Registered user
                        $.ajax({
                            url: "http://localhost:8811/user/registryUser",
                            success: function (result) {
                                resolve(result);
                            },
                            error: function (err) {
                                alert("abnormal" + err)
                            }
                        })
                    } else {
                        // Phone number already exists
                        alert(result.message)
                    }
                });
            })
            .then(result => {
                if (result.data) {
                    alert(result.message)
                }
            })
            .catch(err => {
                alert('Server exception')
            });
    
    //Set up functions to simplify requests
    
        function myAjax(url) {
            return new Promise((resolve, reject) => {
                // 1. Does the requested user name exist
                $.ajax({
                    url,
                    success(result) {
                        resolve(result);
                    },
                    error(err) {
                        reject(err);
                    }
                })
            })
        }
    
        // The authentication user name does not exist
        myAjax("http://localhost:8811/user/existUsername")
            .then(result => {
                if (result.data) {
                    alert('User name does not exist!');
                    return myAjax("http://localhost:8811/user/existPhone")
                } else {
                    alert(result.message)
                }
            })
            // Verify that the phone number exists
            .then(result => {
                if (result.data) {
                    alert('Mobile number does not exist!');
                    return myAjax("http://localhost:8811/user/registryUser")
                } else {
                    alert(result.message)
                }
            })
            // login was successful
            .then(result => {
                if (result.data) {
                    alert(result.message)
                }
            })
            .catch(err => {
                alert('Server exception')
            });
    

What's new in ES6 - modularity

  • What is modularity

    • Modularization is to split the code to facilitate reuse. It is similar to the guided package in java: to use a package, you must use the guided package. However, there is no concept of package in JS. Instead, modules are used.
    • In ES6, each module is a file, and the variables, functions and objects defined in the file cannot be obtained externally
    • Module function
      1. The export command is used to specify the external interface of the module. If you want the external to read the contents of the module, you must use export to expose (output) it. Export can export not only objects, but also all JS variables
      2. The import command imports the module
  • import syntax:

    1. import component name from 'js file path'
    2. Component name = {component to be imported} separate with commas when multiple components are required. When there are many components that need to be used, it can be written directly as *, not {}, but you also need to use as for alias
    3. Non default components must use braces. Default components cannot be written in braces
    <script type="module">
    // import syntax
    // import component name from js file path
    // Component name: {components to be imported} multiple components are separated by commas. Many used components can be written as *, so {} is not required, but as is also required for alias
    // Non default components must use braces. Default components cannot be written in braces
    import * as person form './js/user.js'
    import xxx,{girl} from './js/user.js'
    
    console.info("---"+Object.keys(xxx));
    console.info("----"+girl);
    
    </script>
    
  • Export syntax:

    • Corresponding to three import syntax
      1. Write directly on the component (variables, objects, functions...) (export let User)
      2. Write at the bottom (batch export) (export {User,girl})
      3. Export default
export default {
    username:'Xu Shu',
    age:'18',
    print() {
        console.info(`full name ${this.username},Age:${this.age}`)
    }
}

let girl ={
    realName:'Delireba', 
    cup:'E'
}
 
export {girl}
// Export before import 
// Export 3:
//  1. Write directly on the component (variables, objects, functions...)
//export let User

//  2. Write at the bottom (batch export)
// export {User,girl}

// 3. Export default components

Posted by abch624 on Fri, 01 Oct 2021 10:46:28 -0700