简体   繁体   中英

es6 return dynamically named arrow function

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 ie for debugging.

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}`];
};

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%} 

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:

[ FOO]

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:

FOO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM