phi*_*012 1 javascript ecmascript-6
有没有办法绕过这种行为?
> foo => bar;
[Function]
> const func = foo => bar;
undefined
> func
[Function: func]
Run Code Online (Sandbox Code Playgroud)
我有代码暂时存储这样的匿名函数,然后返回它.我不希望变量名的实现细节像这样暴露.
避免这种情况而不影响代码结构的最简单方法可能是使用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)
(当你在这里时,不要忘记添加一个适当的评论来解释你为什么要这样做)
当然,这可能无法阻止调试器或控制台推断该函数的其他内部名称.
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |