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

后端 未结 10 703
遇见更好的自我
遇见更好的自我 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:42

    Ron S's solution works great but can detect false positives:

    /** Check if function is Arrow Function */
    const isArrowFn = (fn) => (typeof fn === 'function') && /^[^{]+?=>/.test(fn.toString());
    
    /* False positive */
    const fn = function (callback = () => null) { return 'foo' }
    
    console.log(
      isArrowFn(fn)  // true
    )

提交回复
热议问题