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

后端 未结 2 1451
眼角桃花
眼角桃花 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();
    "() => {}"
    

提交回复
热议问题