Reputation: 7212
Although a Functions 'name' property is read-only, is there some trick to set it?
Here's a simplified case where it would help:
class O{
myFn;
constructor(fn){
this.myFn= fn; // Here I want to set the name of fn / this.myFn
}
}
new O( () => {
console.log("hello"); // breakpoint here the function name is "(anonymous function)"
}).myFn();
I could name it at the definition:
new O( function namedFunction () {
console.log("hello");
}).myFn();
but I am looking for a way to name/rename it later.
(I am working on node.js I am not sure if this question would be valid for browsers)
Upvotes: 2
Views: 93
Reputation: 7212
Digging in Function.prototype.name
docs I've found
To change it, you could use Object.defineProperty() though.
(it's at the end of the section https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Inferred_function_names)
So this does what I wanted:
class O{
constructor(fn){
Object.defineProperty(fn,'name',{value:"lateNamedFunction", writable:false});
this.myFn= fn;
}
}
This may provide some interesting possibilities...
Upvotes: 2