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

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

    I wrote this for Node, should work in Chrome as well.

    "Boundness" is detected (apparently, only on ES6) and reported as native && bound. This might or might not be an issue, depending on what you are using that information for.

    const flags = {
      function: f instanceof Function,
      name: undefined,
      native: false,
      bound: false,
      plain: false,
      arrow: false
    };
    
    if (flags.function) {
      flags.name = f.name || '(anonymous)';
      flags.native = f.toString().trim().endsWith('() { [native code] }');
      flags.bound = flags.native && flags.name.startsWith('bound ');
      flags.plain = !flags.native && f.hasOwnProperty('prototype');
      flags.arrow = !(flags.native || flags.plain);
    }
    
    return flags;
    

提交回复
热议问题