JavaScript arrow function

Keywords: Javascript Lambda

 

Arrow function is equivalent to Lambda expression or closure syntax of other languages. Arrow function is a simplified way to write ordinary functions.

The syntax format of the arrow function is as follows:

{pararnl, pararn2,..., pararnN) => {statements }

Amount to:

function (paraml, param2,..., paramN) {

        statements

}

If an arrow function has only one return statement, curly braces and return keywords are allowed to be omitted. In other words, the following two grammars have the same effect:

(paraml, param2, ..., paramN) => expression 
//Equivalent to: (paraml, param2,..., paramn) = > {return expression;}

If the parameter list of an arrow function has only one parameter, parentheses for the parameter list are allowed to be omitted. In other words, the following two grammars have the same effect:

(singlePararn) => {statements} 
//Equivalent to: singleparam = > {statements}

Example arrow function code:

The difference between map() and forEach():

/ / the map() function has a return value, and forEach() has no return value
/ / map() does not work on the original array. Generate an array. forEach() works on the original array

 <script>
        var arr = ['yeek','fkit','leegang','crazyit'];
        // Using functions as parameters of the map () method
        var newArr1 = arr.map(function(ele){
            return ele.length;
        });
        // Use the arrow function as an argument to the map () method
        var newArr2 = arr.map((ele)=>{
            return ele.length;
        });
        // Arrow function, only one parameter, parentheses can be omitted
        // There is only one execution statement, and it is a return statement. You can omit the return keyword
        var newArr3 = arr.map(ele => ele.length);
        console.log(newArr3);

        // Using the function as an argument to the forEach() method
        arr.forEach(function(ele){
            console.log(ele);
        });

         // Use the arrow function as an argument to the forEach() method
        arr.forEach((ele)=>{
            console.log(ele);
        });

         // Arrow function, only one parameter, parentheses can be omitted
        // There is only one execution statement, and curly brackets of the execution body can be omitted
        arr.forEach(ele => console.log(ele));
    </script>

    
    <script>
        // When there is no parameter, the parentheses of the parameter list cannot be omitted
        var f = ()=>{
            console.log("test");
            console.log("end");
        }
        // Execute f function
        f();
    </script>

Operation result:

 

Unlike ordinary functions, arrow functions do not have their own this keyword

——For a normal function, if the program creates an object through a new call function, then this in the function represents the created object; if the normal function is called directly, then this in the function represents the global object (window).

Code example:

    <script>
        function Person(){
            // Instance property this
            this.age = 0;
            // Global method, timer once in 1000 milliseconds
            setInterval(function growUp(){
                // For a normal function, this represents the global object (window) when the function is executed directly 
                console.log(this === window);
                this.age++;
                console.log(this.age);//The age value of the global object under window is uncertain, so NaN is output
            },1000)
        }
        // 1. Get the object p 2 and call the Person function
        var p = new Person();
        setInterval(function(){
            console.log(p.age);//When accessing the age of p object here, it will always output 0 
        },1000);
    </script>

Operation result:

this in the arrow function always represents the context containing the arrow function.  

If the arrow function is defined directly in the global scope, the context of the arrow function is window itself, and this in the arrow function represents the global object window

Code example:

    <script>
        function Person(){
            // Instance property this
            this.age = 0;
            // Global method, timer once in 1000 milliseconds
            setInterval(() => {
                // this in the arrow function always represents the context containing the arrow function 
                console.log(this === window);
                //This here is exactly the same as this in the Person constructor 
                this.age++;
                console.log(this.age);//If this is the age under Person, the output value will always be increased by 1 
            },1000)
        }
        // 1. Get the object p 2 and call the Person function
        var p = new Person();
        setInterval(function(){
            console.log(p.age);//When accessing the age of the p object, the output value will always be incremented by 1 
        },1000);
    </script>

Operation result:

 

The arrowhead function does not bind arguments, so arguments cannot be used in the arrowhead function to access the arguments that call the arrowhead function. Arguments in the arrow function always refer to arguments in the current context.

Arguments: the implicit argument arguments passed to the function by the browser.

When a function is called, the browser passes in two implicit parameters each time:

1. Context object this of function

2. Encapsulating arguments

Code example:

    <script>
        var arguments = "li";
        //Arguments in the arrow function refer to arguments in the current context 
        var arr = ()=>arguments;
        //"li" in output context
        console.log(arr());
        function foo(){
            //Arguments in the arrow function refer to arguments in the current context 
            //At this point, arguments represent the parameters of the foo function 
            var f = (i) => 'hello,'+arguments[i];
            //Pass in parameter 1 -- > to i
            return f(1);
        }
        console.log(foo("china","dadaguai","dog"));
    </script>

Operation result:

 

In the above code, arguments have values, whose values are the parameters we pass in. Although we have not defined parameters for the foo function, we can still call the arguments passed to the foo function through arguments.

 

Because the arrow function is easy to write code, it is easy to make mistakes:

1. Error returned by function

{name:'li'} enclosed by curly brackets is an Object object Object

<script type="text/javascript ">
 var f =() => {name:'li'};
 console.log(f()) ; 
</script>

But the above program is restored to normal form:

   <script type="text/javascript">
        var f =function(){
            return name:'li'   //Procedure error reporting
        };
        console.log(f()) ; 
    </script>

Correct form: {name:'li'} enclose it in parentheses

 <script type="text/javascript ">
        var f =() => ({name:'li'});
        console.log(f()) ; 
</script>

 

Arrow functions do not allow line breaks between parameter lists and arrows; otherwise, a syntax error will be prompted. For example, the following functions will prompt for syntax errors:
 

var func = () 
=> 'Hello';

Correct form:

var func = () => 
'Hello';

2. Errors caused by parsing order

Although arrow functions contain arrowheads that are not operators, they can also cause errors due to the parsing order when they are with other operators.

var func;
func = func || () => "yu" ; 

The program first processes func ll(), which causes code errors.  

 

Published 21 original articles, won praise 2, visited 1058
Private letter follow

Posted by micklerlop on Thu, 06 Feb 2020 04:28:09 -0800