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