Side effects of arrow function

Time:2021-7-3

1、 Preface

In the project, I am used to using arrow function wherever I can, so that I don’t have to worry about the problem of this action at any time, and it’s very convenient for writing. Also searched related articles, which also suggest using arrow function as far as possible. Of course, the arrow function is not omnipotent, certainly can not replace the ordinary function.
So, what should arrow function pay attention to?

2、 Some common problems

(the code is tested on the console)

1. The direction of scope this

This points to the place created or instantiated;

  • Object method,
let A = {
    a:'a',name:()=>console.log(this,this.a)
}
console.log(A);// S {a: "a", name: ƒ}
console.log(A.name());//
  • The method of prototype
function A(){
    this.a = "a";
}
A.prototype.name = ()=>console.log(this,this.a);
(new A).name();// Window, undefined, this. A's this points to window
  • Callback function in dynamic context

2. Cannot be new, cannot be constructor

3. The arguments parameter needs to be obtained

3、 Performance issues

class F{
    f = ()=>{
        console.log('f');
    }
    fp(){
        console.log('fp');
    }
}

class B extends F{
    b = ()=>{
        console.log('f');
    }
        bp(){
        console.log('bp');
    }
}
let fc = new F();
let fc2 = new F();
let bc = new B();
console.log(fc,fc2,bc);
console.log(fc2.f == fc.f);//false
console.log(fc.f == bc.f);//false
console.log(fc.fp == bc.fp);//true

We find that f (arrow function) is not inherited, and every time it is created, it is a copy.

4、 Summary
The problems in the second part of “some common problems” above can not offset the convenience brought by arrow function. On the contrary, ordinary functions have various problems.
Although arrow function improves productivity and frees the time for us to think about this for scenarios with low performance requirements, it still needs to be evaluated for scenarios with high performance requirements.

reference resources:
https://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6#:~:text= Arrow functions should not be used%3A ,want to use named function
as arrow… More

https://wesbos.com/arrow-function-no-no