How to programmatically distinguish an arrow function from a regular function?

后端 未结 2 1435
眼角桃花
眼角桃花 2021-01-01 03:33

There is no obvious difference between an arrow function and a regular function.

({}).toString.call(function () {})
\"[object Function]\"
({}).toString.call(         


        
相关标签:
2条回答
  • 2021-01-01 03:59

    The best I can think of is using toString:

    let isArrowFunction;
    
    isArrowFunction = (fn) => {
        console.log(fn.toString());
    
        return fn.toString().indexOf('function') !== 0;
    };
    
    console.log(isArrowFunction(() => {}) === true);
    console.log(isArrowFunction((foo: string) => {}) === true);
    console.log(isArrowFunction(function () {}) === false);
    

    See:

    (function () {}).toString();
    "function () {}"
    
    (() => {}).toString();
    "() => {}"
    
    0 讨论(0)
  • 2021-01-01 04:21

    Uhm, the requirements are a bit weird, but I made some tests and:

    typeof (() => {}).prototype === "undefined"
    

    Is true, while:

    typeof (function () {}).prototype === "undefined"
    

    Is false, so:

    function isArrow(x)
    {
      return typeof (x.prototype) === "undefined"
    }
    

    Fiddle here: https://jsfiddle.net/87kn67ov/

    0 讨论(0)
提交回复
热议问题