1

I'm wondering if there is a way to completely change the name of a function constructed via the Function constructor.

First of all, I tried to create a new Function, which then in turn seems to have the name anonymous:

const fnName = 'test';
const fn = new Function('a', 'b', 'c', 'console.log("function works");');

Then I found out that while the fn.name property is not writable, it seems to be configurable in ES2015. So I went ahead and changed it using Reflect.defineProperty:

Reflect.defineProperty(fn, 'name', { configurable: true, value: fnName });
console.log(fn.name); // 'test'

When I output the function to string, it still had the name anonymous, so I overwrote the toString function:

const originalToString = fn.toString;
fn.toString = function() {
    return originalToString.call(this).replace('anonymous', fn.name);
}
fn.toString();
// "function test(a, b, c) {
// console.log("function works");
// }"

Yet I can't figure out how I can change the name that is shown when I put it into the console:

enter image description here

Is there any way to do this or is this just some internal property of the JS runtime that can't be touched?

PS: This is a purely academical question.

nils
  • 25,734
  • 5
  • 70
  • 79
  • *"When I output the function to string, it still had the name anonymous"* What [`toString`](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-function.prototype.tostring) returns is implementation dependent. It seems like the spec makes any requirements regarding the name. *"I can't figure out how I can change the name that is shown when I put it into the console"* There is no specification for console output. In order to change the output, you'd have a look at the implementation your are interested in and see how it computes the output from the value you pass. – Felix Kling Mar 24 '16 at 18:49
  • There's [a way](http://stackoverflow.com/questions/5871040/how-to-dynamically-set-a-function-object-name-in-javascript-as-it-is-displayed-i), but it's hacky. – Dan Prince Mar 24 '16 at 18:50
  • @DanPrince nice, that seems like a neat, hacky way of doing it. – nils Mar 24 '16 at 19:05
  • @FelixKling good to know, thank you. – nils Mar 24 '16 at 19:05
  • What are you actually trying to do though? Sounds like [XY Problem](http://www.perlmonks.org/?node_id=542341) – Mulan Mar 25 '16 at 06:31
  • @naomik It does sound like one at first glance. To quote myself though: *PS: This is a purely academical question.* I was just learning how the Function constructor works and thus curious if there was a way to create a named function. – nils Mar 30 '16 at 11:53

0 Answers0