Skip to content Skip to sidebar Skip to footer

In Es2015, `const Func = Foo => Bar` Makes `func` A Named Function, How Do You Bypass This?

Is there any way to get around this behavior? > foo => bar; [Function] > const func = foo => bar; undefined > func [Function: func] I have code that temporarily sto

Solution 1:

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;

constfunc = 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 evalconst func4 = [foo => bar][0]; // member access on array literalconst 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.

Solution 2:

This is not related to ECMAScript.

It's true that, when you assign an anonymous function a variable, the name of the function will be set to the name of the variable (thanks @loganfsmyth for the correction).

Since name is a configurable property, you could delete it. However, that would be useless, because name is unrelated.

For example, Firefox hasn't implemented naming anonymous functions as the variables yet, so name is the empty string in your example. But the console still displays function func() when you log the function.

In fact, the "problem" is that browsers want to make debugging code easier, so their console infers a name (not necessarily the name) for the function.

Engines can infer function names gives this example of inference:

Anonymous functions no longer need to be named for debugging

functionf() {}            // display name: f (the given name)var g = function () {};    // display name: g
o.p = function () {};      // display name: o.pvar q = {
  r: function () {}        // display name: q.r
};
functionh() {
  var i = function() {};   // display name: h/if(function () {});       // display name: h/<
}
var s = f(function () {}); // display name: s<

The consoles of the browsers are not standardized by ECMAScript, so you can't modify this behavior.

Post a Comment for "In Es2015, `const Func = Foo => Bar` Makes `func` A Named Function, How Do You Bypass This?"