JavaScript ES6: Test for arrow function, built-in function, regular function?

后端 未结 10 730
遇见更好的自我
遇见更好的自我 2020-11-27 06:16

Is there an elegant way to tell Harmony\'s slim arrow functions apart from regular functions and built-in functions?

The Harmony wiki states that:

10条回答
  •  日久生厌
    2020-11-27 06:22

    • Convert Function to string toString
    • removing all spaces of this string.
    • if ")=>" exists with index greater or equal to 1 => 99.99% is an arrow function .

          F.toString().replace(/\s+/g, '').indexOf(')=>')>=1
      

    DEMO :

    var fn1=function(e){
       e.target.value=new Date();
    };
    
    var fn2=(a,b)=> a+b;
    
    function isArrow(name,F){
             if(F.toString().replace(/\s+/g, '').indexOf(')=>')>=1){
                     console.log(`${name} is arrow-function`);
             }else{
               console.log(`${name} is classic-function`);
              }
    }
    
    isArrow('fn1',fn1);
    isArrow('fn2',fn2);

提交回复
热议问题