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