Basic usage

// No arguments multiple arguments need to be wrapped around ()
const fn = () = >5
console.log(fn());
const fnG = (num1,num2) = >num1 + num2
console.log(fnG(1.2));
Function blocks containing more than one statement are wrapped with {} and returned with a return
const fJ = (a,b) = >{
    let c = a+b;
    let d = c+19;
    return d
}
console.log(fJ(1.7));
// Return an object {}
let getObj = () = >({name:'Joe'.age:18})
console.log(getObj());
let getObj1 = () = >{
    return {
        name:'Joe'.age:18}}console.log(getObj1());
Copy the code

Pay attention to the point

// 1 This is where the arrow function is most useful. This is no longer the object that is defined dynamically instead of the object that is used
// 2 arrow functions cannot be used as constructors
// Arguments cannot be used inside arrow functions
// 4 cannot be used as a generator
Copy the code

Examples demonstrate

// See the code
function Person(){
    this.name = 'Joe'
    this.say = function(){
        console.log('This is my nameThe ${this.name}`); 
    }
    this.say = this.say.bind(this)
    // this.say = ()=>{
    // console.log(' This is my name ${this.name} ');
    // }
}
let person = new Person()
let res = person.say
res()
Copy the code

Use time

// When the arrow function is used
// 1 If a short statement returns a simple expression return num + num 2 There is no reference to this inside the function
// No reference of its own (recursive)
// 2 Internal need to call VAT self = this call bind also applies to the arrow function
// 3 There is nothing wrong with using arrow functions as long as it is a callback function
Copy the code

Scenarios where arrow functions are not applicable

  1. Call this in the EVENT of a DOM binding to get the value of one of its properties

    document.querySelector('#textBtn').oninput = () = > {
       console.log(this.value); // undefined
    };
    Copy the code
  2. Change this of the arrow function with call, apply, and bind

    // apply
    const A = (age, gender) = > {
      this.age = age;
      this.gender = gender;
    };
    const a = {};
    A.apply(a, [18.'gender']);
    console.log(a); / / {}
    
    // bind
    const test = () = > {
    	console.log(this.gender); // window.gender => undefined
    };
    const obj = {
    	gender: 'male'};const bindTest = test.bind(obj);
    bindTest();
    Copy the code
  3. Think of the arrow function as a constructor

    const A = () = > {};
    const a = new A(); / / an error
    Copy the code
  4. Use arguments objects in constructors

    const a = () = > {
      console.log(arguments); // arguments undefined
    };
    Copy the code
  5. Use the arrow as a generator

    const a = *() = > {}; // The compiler has a syntax error
    Copy the code