设置匿名函数的名称

Set anonymous function's name

虽然函数 'name' 属性 是只读的,但是有什么技巧可以设置它吗?

这里有一个简化的案例,它会有所帮助:

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();

我可以在定义中命名它:

new O(  function namedFunction () {      
    console.log("hello");  
}).myFn();

但我正在寻找一种方法 name/rename 它稍后。

(我正在研究 node.js 我不确定这个问题对浏览器是否有效)

深入研究我找到的 Function.prototype.name 文档

To change it, you could use Object.defineProperty() though.

(在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Inferred_function_names部分的末尾)

这就是我想要的:

class O{
    constructor(fn){

        Object.defineProperty(fn,'name',{value:"lateNamedFunction", writable:false});

        this.myFn= fn;
    }
}

这可能会提供一些有趣的可能性...