es6 return dynamically named arrow function

2019-08-09 17:23发布

问题:

If possible, what is the simplest way to return a named arrow function?

const add = a => b => b + a
const add5 => add(5)

add.name == 'add' // true
add5.name == '' // true, but I would like it to be 'add5'

So, as one can see the in example above, the returned arrow function is anonymous and I would like it to be named (ideally based on the 'parent' function and the 'parameter' a) — which is useful i.e. for debugging.

回答1:

You can do this:

const add = a => (({[`add${a}`]: b => b + a})[`add${a}`]);
const add5 = add(5);

console.log(add5.name);

How it works: define a local object and assign the arrow method as a member with your desired name:

const add = a => {
  const o = {
    [`add${a}`]: b => b + a
  };
  return o[`add${a}`];
};


回答2:

This isn't exactly the same, but:

const add = a => b => a + b;
const add5 = (...a) => add(5)(...a);

console.log(add5(100));  // => 105
console.log(add5.name);  // => 'add5'
div{min-height:100%}



回答3:

This example demonstrates how arrow function names are assigned, and this behaviour cannot be changed. Arrow function name is equal to the name of a variable or object property it was assigned to.

name is non-writable property but is configurable in most implementations, including evergreen browsers, so it's safe to use for debugging purposes:

function namedArrow(name, fn) {
  Object.defineProperty(fn, 'name', { enumerable: false, value: name });
  return fn;
}

const foo = namedArrow('foo!', () => { throw new Error });
foo();

It outputs:

[

For debugging purposes displayName can be used also, which is supposed to play same role and is supported by some debuggers and browser debugger tools, notably Firefox and Chrome:

function namedArrow(name, fn) {
  fn.displayName = name;
  return fn;
}

It results in similar output, yet it doesn't play well with Error call stack: