在es2015中,`const func = foo => bar`使`func`成为一个命名函数,你如何绕过它?

phi*_*012 1 javascript ecmascript-6

有没有办法绕过这种行为?

> foo => bar;
[Function]
> const func = foo => bar;
undefined
> func
[Function: func]
Run Code Online (Sandbox Code Playgroud)

我有代码暂时存储这样的匿名函数,然后返回它.我不希望变量名的实现细节像这样暴露.

Ber*_*rgi 5

避免这种情况而不影响代码结构的最简单方法可能是使用identity函数来包装定义:

const id = x => x;

const func = id( foo => bar );
console.log(func.name) // undefined
Run Code Online (Sandbox Code Playgroud)

如果您不想声明辅助函数,也可以将其内联,或使用IIFE:

const func1 = (f=>f)( foo => bar );
const func2 = (()=> foo => bar )();
Run Code Online (Sandbox Code Playgroud)

但基本上除了分组运算符(带括号的表达式)之外的任何东西都可以:

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
Run Code Online (Sandbox Code Playgroud)

(当你在这里时,不要忘记添加一个适当的评论来解释你为什么要这样做)

当然,这可能无法阻止调试器或控制台推断该函数的其他内部名称.

  • @Asad:FF还没有完整的ES6支持(我不知道有任何引擎).特别是,它[完全不支持函数`.name`](https://kangax.github.io/compat-table/es6/#function_name_property) (2认同)