[ES6] Arrow function

One: Definition of arrow function

Basic syntax:

        //ES5的函数语法
        //定义式
        let fn=function(){
            console.log(11);
        }
        fn()//11
        //声明
        function fn1(){
            console.log(222);
        };
        fn1()//222
        //ES6箭头函数
        let fn2=()=>{//简单明了,没有function开头了使用"=>"代替
            console.log(3333);
        };
        fn2();//3333

When the arrow function has only one parameter, the parentheses () can be omitted       

        let fn=a=>{//接受了一个实参,括号可以取消
            console.log(a);
        };
        fn(6)//6

Conversely, if multiple parameters are used, parentheses () must be used

        let fn1=(a,b,c)=>{//接受多个参数需要添加括号,不然会报错,代码不会运行
            console.log(a,b,c);
        };
        fn1(10,20,30);//10 20 30

If the execution body of the arrow function has only one expression that is the return value, then the curly braces can be omitted.

        let fn=(a,b)=>a+b;
        let num= fn(10,20);
        console.log(num);//30

When the arrow function returns an object, in order to distinguish it from the code block, the object should be wrapped with ().

        let f = (a, b) => ({ id: a, name: b });
        let obj = f(11, "小明");  
        console.log(obj);//{id: 11, name: '小明'}

The this inside the arrow function is not the caller of the arrow function, but the outer scope of the arrow function.

        let fn=(a,b)=>{
            console.log(this);//此时的 this 是外层的 this 对象,即 Window 
            return a+b
        };
        let obj={name:"小明",fn}
         let num=obj.fn(10,20); //这里按理说fn被调用,函数里面的this就该指向obj,结果却不是
         console.log(num);//30
        //而使用普通函数则是指向的obj
        let fn1=function(a,b){
            console.log(this);//obj
            return a+b
        };
        let obj1={name:"小明",fn}
         let num1=obj.fn(10,20);
         console.log(num);//30

Arrow functions cannot be used as constructors, that is, the new command cannot be used, otherwise an error will be reported

        let fn=function(){
             console.log(this);
        };
        new fn();//fn {}
        //使用箭头函数会报错
        let fn1=()=>{
            console.log(this);
        };
        new fn1()//报错

Two: Points to note when using arrow functions

(1) The arrow function does not have its own this object.
(2) It cannot be used as a constructor, that is, the new command cannot be used for arrow functions, otherwise an error will be thrown.
(3) The arguments object cannot be used, which does not exist in the function body. If you want to use it, you can use the rest parameter instead.
(4) For methods in the object, try not to use arrow functions
(5) The this in the arrow function always points to the this inside the closest function;


———————————————

Original link: https://blog.csdn.net/webxuj/article/details/125747170

Guess you like

Origin blog.csdn.net/sun_qqq/article/details/130621906