[ES6] ES6 understanding and syntax

Why learn es6?

  1. es5 congenital deficiency
  2. The vue react framework uses es6. The author initially thought that he could not understand vue, but later found out that he actually could not understand es6 syntax/(ㄒoㄒ)/~~
  3. Currently most companies are using es6

ES6 is the standard for the JS language. The goal is to be able to write complex large-scale applications and become an enterprise-level development language.
Babel: called the next generation JS compiler, can turn es6 into es5.

ES6 new features

let and const commands

Let and const are used to declare the variable
let in the same way as var:

    //这样写会把a变量提升到最上面,但是不赋值,所以会打印undefined
    console.log(a);
    var a = 2;

    //这样写会报错,因为let不会提升变量
    console.log(b);
    let b = 10;

    //let是一个块级作用域
    console.log(c1) //不报错
    console.log(c2) //报错
    if(true){
    
    
        var c1 = 1;
        let c2 = 1;
    }

    // let 不能重复声明 , var就可以
    let d = 1;
    let d = 2; //报错

const: In addition to the three restrictions of let, it also has the characteristic that it cannot be changed once declared, which is equivalent to declaring a constant.

es6 template string

In the past, if you wanted to concatenate a string, you had to do this

    <div class="box">
    </div>

    <script>
        const oBox = document.querySelector('.box');
        let id = 1,
            name = "小帅";
        oBox.innerHTML = "<ul><li><p id="+id+">"+name+"</p></li></ul>"
    </script>

es6 can quickly add template strings

    <script>
        const oBox = document.querySelector('.box');
        let id = 1,
            name = "小帅";
        
        let htmlStr = `<ul>
            <li>
                <p id='${ 
        id}'>${ 
        name}</p>
            </li>
        </ul>`;
        oBox.innerHTML = htmlStr;
    </script>

Enhanced functions

Assign default value operation

    //es5
    function add(a,b) {
    
    
        a = a || 10;
        b = b || 20;
        return a+b;
    }
    //es6
    functon add(a = 10 , b = 20){
    
    
        return a+b ;
    }

The default expression can also be a function

    function getVal(val){
    
    
        return val+5;
    }
    //默认值可以直接为表达式
    function add(a,b = getVal(5)){
    
    

    }

remaining parameters

    let book = {
    
    
        title:"aa教程",
        author:'zs',
        year:2023
    }
    //eas5 写法
    function pick5(obj) {
    
    
        let result = Object.create(null);
        for(let i = 1; i < arguments.length ; i++){
    
    
            result[arguments[i]] = obj[arguments[i]];
        }
        return result
    }
    //es6 剩余参数的写法 由三个点和一个紧跟着的具名参数指定
    function pick6(obj,...keys) {
    
    
        let result = Object.create(null);
        for(let i = 0 ; i < keys.length ; i++){
    
    
            result[keys[i]] = obj[keys[i]];
        }
        return result;
    }
    let bookData5 = pick5(book,'author','year');
    let bookData6 = pick6(book,'author','year');
    console.log(bookData5);
    console.log(bookData6);

spread operator

    //剩余运算符,把多个独立的合到一个数组中
    //扩展运算符:将一个数组分割,并且将各个项作为分离的参数传给函数
    const arr = [10,20,30,50,60,100];
    console.log(Math,max.apply(null,arr)); //es5写法
    console.log(Math.max(...arr));  //扩展运算符写法

arrow function

    //使用 => 来定义 
    // function(){}等于 ()=>{}
    let add = function(a,b) {
    
    
        return a+b;
    }
    //es6写法
    let add6 = (a,b)=>{
    
    
        return a+b;
    }
    //一个参数
    let add1 = val => {
    
    
        return val+5;
    }
    //再简便就是
    let add2 = val => (val+5);

    //函数嵌套
    let fn = (() => {
    
    
        return () => {
    
    
            console.log('hello world');
        }
    })();
    fn();

    //箭头函数的this绑定
    let PageHandle5 = {
    
    
        id:123,
        init:function (){
    
    
            document.addEventListener('click',function(event) {
    
    
                this.doSomethings(event,type);
            }.bind(this),false)
        },
        doSomethings:function(type){
    
    
            console.log(`事件类型:${
      
      type},当前id:${
      
      this.id}`);
        }
    }
    PageHandle5.init();
    //es6
    let PageHandle6 = {
    
    
        id:123,
        init:function (){
    
    
            document.addEventListener('click',(event) => {
    
    
                this.doSomethings(event,type);
            },false)
        },
        doSomethings:function(type){
    
    
            console.log(`事件类型:${
      
      type},当前id:${
      
      this.id}`);
        }
    }
    PageHandle6.init();

Note
1. There are no arguments inside arrow functions
2. Arrow functions cannot use the new keyword to instantiate objects

Destructuring assignment

Destructuring assignment is an extension of the assignment operator
. It operates on arrays and objects.
Advantages: Concise code writing

    let node = {
    
    
        type : "c",
        name : "zs"
    }
    //es5
    let type = node.type;
    let name = node.name;
    //es6 - 完全解构
    let {
    
    type,name} = node;

    //再如 - 不完全解构
    let obj = {
    
    
        a:{
    
    
            name:'张三'
        },
        b:[],
        c:'helloWorld'
    }
    let {
    
    a} = obj
    //可以使用剩余运算符
    let {
    
    a,...res} = obj;

    //也可以对数组进行解构,参数名随便取

Extended string, object, array functions

Extended object functionality:

  1. es6 directly writes variables and functions as properties and methods of objects
    const name = 'zs',age = 20;
    const person = {
    
    
        name, //等价于name:name
        age
        sayName(){
    
    
            console.log(this.name);
        }
    }

    //可以出来给对象添加值,用[]来拼接名字
    const obj = {
    
    };
    obj.isShow = true;
    const name = 'z';
    obj[name + 's'] = 21;
    console.log(obj);

is() ===

    //比较两个值是否严格相等
    console.log(NaN === NaN) //false,特殊
    //is()是严格比较,啥都相同
    Object.is(NaN,NaN);

assign()

    //对象的合并
    //Object,assign(target,obj1,obj2,....)
    let target = {
    
    
        name:'zs'
    }
    target = Obj.assign(target,{
    
    a:1},{
    
    b:2});

Symbol

Symbol is a new primitive data type provided by es6.
It represents a unique value.

    const name = Symbol('name');
    const name2 = Symbol('name');
    console.log(name === name2) //false

His biggest use: used to define private variables of objects

    let s1 = Symbol('s1');
    console.log(s1); //Symbol('s1')
    let obj = {
    
    };
    obj[s1] = 'zs';
    //或者这么直接复制
    let obj2 = {
    
    
        [s1]:'zs'
    }
    //如公用Symbol定义对象中的变量,取值时一定用[变量名]
    console.log(obj[s1]);

    //通过反射得到Symbol声明的属性名 (作为对象的key)
    const syms = Object.getOwnPropertySymbols(ibj);
    console.log(syms[0]);

    let syms1 = Reflect.ownKeys(obj);

Map and Set

Set: an ordered list without duplicate values

    let set = new Set();

    //添加元素 ,任意类型
    set.add(2)// 删除元素
    set.delete(2);
    set.has(2); //判断有无
    set.size; //大小

    //将set转换成数组
    let set2 = new Set([1,2,3,4,5,6,7,8]);
    let arr = [...set2]; // 通过扩展运算符来进行操作

    //set中对象的引用无法被释放
    let set3 = new Set(),obj = {
    
    };
    set.add(obj);

    obj = null; //释放资源 , 这里无法释放
    //解决方法- 使用WeakSet
    let set4 = new WeakSet(),obj2 = {
    
    }
    set.add(obj2);
    obj = null; //这里可以直接释放,set4中的obj2没了

WeakSet
1. Cannot pass in non-object type parameters
2. Not iterable
3. No forEach()
4. No size

Map: is an ordered list of key-value pairs. The keys and values ​​are of any type. Set is a Map whose keys are equal to the values.

    let map = new Map();
    map.set('key','value');

    //或者这样创建
    let map2 = new Map(['key1','value1'],['key2','value2']);
    //forEach遍历
    map.forEach((val,key) =>{
    
    

    })

Guess you like

Origin blog.csdn.net/qq_67548292/article/details/131724727