What is an arrow function

Take an ordinary function expression as an example.

let sum = function  (a,b){console.log(a+b)}
Copy the code

The syntax for the arrow function should be:

let sum = (a,b)=>{console.log(a+b)}
Copy the code

In fact, it is very simple to put the argument list in parentheses and the function body in curly braces.

Parameter to the arrow function

The default form is

(a,b,c........)
Copy the code

But the parentheses can be omitted when there is only one parameter

a=>{consloe.log(a)}
Copy the code

The body of the arrow function

If there is only one line in the function body, you can omit the curly braces, and the result of the function body is returned. For example: a=>{return a; } is equivalent to a=>a

The arrow function this points to

The arrow function’s this point, I think remember one thing, its this point is the same as the this point in the nearest scope. Here’s an example:

setTimeout(function(){console.log(this)},100);
setTimeout(()=>console.log(this),100);
Copy the code

What do these two this outputs? The first one, this, was mentioned in the previous article. Functions in setTimeout/setInterval point to window by default. The second “this” refers to the “this” of the nearest scope, which should be the global scope. This in the global scope should be window.

let obj = { a:function(){ setTimeout(()=>console.log(this),1000); }}Copy the code

This should refer to object A.