简体   繁体   English

JavaScript:将内部函数的名称设置为分配给它的变量的名称

[英]JavaScript: Set name of inner function to be name of variable it's assigned to

I'm trying to do some composition and I'm using the function name to assign a key in an object. 我正在尝试进行一些组合,并且正在使用函数名称在对象中分配键。 Thus, I have a higher order function kind of like so: 因此,我有一个像这样的高阶函数:

function doThing(fn) {
  return function (...args) {
     return fn(...args);
  };
}

And I'm assigning the result of the outer function to a variable: 我将外部函数的结果分配给一个变量:

var coolThing = doThing(someFunction);

I want coolThing.name to equal 'coolThing' . 我想要coolThing.name等于'coolThing'

Now I'm pretty sure that is impossible because once the inner function is returned, the name is set to an empty string and can no longer be changed. 现在,我非常确定这是不可能的,因为一旦返回内部函数,该名称将设置为空字符串,并且无法再更改。 But I'm wondering if I can elegantly make something like it work without skirting the lexer or anything awful like that. 但是我想知道我是否可以优雅地使类似的东西工作而不会跳过词法分析器或类似的事情。

Just wrapping doThing(someFunction) with another function would make it work, but that ends up making it no better than what I had started with. 只是将doThing(someFunction)与另一个函数包装doThing(someFunction)就可以使它工作,但是最终使它不比我开始时做的更好。

It doesn't have to be the name property that I'm using, but the function needs to have some property that get's its value from the name of the variable. 它不必是我正在使用的name属性,但是该函数需要具有一些可以从变量名称中获取其值的属性。

Any ideas, or am I trying to be too cute here? 有什么想法吗,还是我想在这里变得太可爱了?

I'm pretty sure that is impossible 我很确定那是不可能的

You're right. 你是对的。 The variable name is not accessible programmatically, and for sure not inside doThing . 变量名不能通过编程方式访问,并且肯定不能在doThingdoThing Even for function declarations and assigned anonymous function expressions, the implicitly assigned .name property is something that the runtime does extract from the source text for exactly those syntactic constructs. 即使对于函数声明和分配的匿名函数表达式,隐式分配的.name属性也是运行时确实从源文本中提取的那些语法构造的东西。 It can not be intercepted and should only be used for debugging purposes anyway. 它不能被截获,无论如何仅应用于调试目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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