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

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

    I couldn't find false positives. Small change to Ron S's approach:

    const isArrowFn = f => typeof f === 'function' && (/^([^{=]+|\(.*\)\s*)?=>/).test(f.toString().replace(/\s/, ''))
    
    const obj = {
        f1: () => {},
        f2 () {}
    }
    
    isArrowFn(obj.f1) // true
    isArrowFn(() => {}) // true
    isArrowFn((x = () => {}) => {}) // true
    
    isArrowFn(obj.f2) // false
    isArrowFn(function () {}) // false
    isArrowFn(function (x = () => {}) {}) // false
    isArrowFn(function () { return () => {} }) // false
    isArrowFn(Math.random) // false
    

提交回复
热议问题