es6返回动态命名的箭头函数 [英] es6 return dynamically named arrow function

查看:128
本文介绍了es6返回动态命名的箭头函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果可能,返回命名箭头函数的最简单方法是什么?

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'

因此,如上例所示,返回的箭头函数是匿名的,我希望将其命名(理想情况是基于父"函数和参数" a)—这很有用即用于调试.

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.

推荐答案

您可以执行以下操作:

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

console.log(add5.name);

工作原理:定义一个本地对象,并将arrow方法指定为具有您想要的名称的成员:

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

这篇关于es6返回动态命名的箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆