Arrow function

Syntax :(parameter)=>{function body}

Example:

const fn = () = > {
  console.log(123);
};
fn();/ / 123
Copy the code
  • The arrow function is used to simplify function definition syntax

  • There is only one line of code in the function body, and the result of the code execution is the return value. You can omit the curly braces

function sum (num1 , num2) {
return num1 +num2 ;
} 
/ / equivalent to
const sum = (num1 , num2) = >num1 + num2;
console.log(sum(1.3));/ / 4
Copy the code
  • If the parameter has only one, you can omit the parentheses
function fn (v){
    return v;
}
/ / equivalent to
const fn1 = v= > v;
console.log(fn1(5));
Copy the code
  • Arrow functions don’t bind this. Arrow functions don’t have their own this keyword, so if we use this in arrow functions,

The this keyword points to this in the scope where the arrow function is defined

const obj = { name: "Zhang" };
function fn2() {
  console.log(this);//{name: 'zhang3'}

  return () = > {
    console.log(this);
  };
}
const resFn = fn2.call(obj);
resFn();  //{name: 'zhang3'}
Copy the code

The first this is the this that is changed by call to point to obj. The second this is the this in the arrow function that points to this in the current scope, that is, this in fn2

var age =100;
var obj = {
    age: 20.say:() = >{
    console.log(this.age)
    }
}
obj.say();  / / 100
Copy the code

Since there is no scope in the object, this in the arrow function points to the window, so obj.say() outputs the age of the window with a value of 100