Arrow function

Characteristics of the arrow function

  • The problem with this pointing is that for normal functions it points to whoever is called but for arrow functions the reference to this is the context in which the arrow function is defined

Code example -1

var name = 'jsck';
    let obj = {
    age: 12,
    name: 'mary',
    sayHi: function() {
        console.log(this.name);
    }
}
let obj_a = {
    age: 12,
    name: 'mary',
    sayHi: () =>  {
        console.log(this.name);
    }
}
obj.sayHi(); // mary
obj_a.sayHi(); //  jsck

Copy the code

Obj_a calls sayHi, but since it’s an arrow function I’m writing it in global mode so this points to the window

Code example -2

var name = 'jack'
function King() {
    this.name = 'mary';
    setTimeout(() => {console.log(this.name)}, 2000)
}
function Queen() {
    this.name = 'mary';
    setTimeout(function(){
        console.log(this.name);
    }, 2000)
}
let k = new King(); // mary
let q = new Queen(); // jack
Copy the code
  • The arrow function has no prototype of its own. Note that it is constructor

As a result, it has no way to use new as a constructor

– The arrow function has no argument but can take arguments by extending the operator

let f = (... values) => { console.log(values); } f(1, 2, 3) // [1, 2, 3];Copy the code