简体   繁体   中英

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' .

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.

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.

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 . 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. It can not be intercepted and should only be used for debugging purposes anyway.

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