In es2015, `const func = foo => bar` makes `func` a named function, how do you bypass this?

后端 未结 2 706
走了就别回头了
走了就别回头了 2021-01-24 10:05

Is there any way to get around this behavior?

> foo => bar;
[Function]
> const func = foo => bar;
undefined
> func
[Function: func]
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 10:52

    The simplest way to avoid this without affecting your code structure is probably to use the identity function to wrap the definition:

    const id = x => x;
    
    const func = id( foo => bar );
    console.log(func.name) // undefined
    

    If you don't want to declare a helper function, you can inline it as well, or use an IIFE:

    const func1 = (f=>f)( foo => bar );
    const func2 = (()=> foo => bar )();
    

    but basically anything except the grouping operator (a parenthesised expression) will do:

    const func3 = (0, foo => bar); // comma operator, known from indirect eval
    const func4 = [foo => bar][0]; // member access on array literal
    const func5 = true ? foo => bar : null; // ternary operator
    

    (And while you're at it, don't forget to add an appropriate comment that explains why you're doing this)

    Of course, that might not prevent a debugger or console from inferring some other, internal name for the function.

提交回复
热议问题