简体   繁体   English

设置匿名函数的名称

[英]Set anonymous function's name

Although a Functions 'name' property is read-only, is there some trick to set it?尽管 Functions 的“名称”属性是只读的,但是否有一些技巧可以设置它?

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) (我正在研究 node.js 我不确定这个问题是否对浏览器有效)

Digging in Function.prototype.name docs I've found挖掘我发现的Function.prototype.name文档

To change it, you could use Object.defineProperty() though.要更改它,您可以使用 Object.defineProperty() 不过。

(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 ) (它在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...这可能会提供一些有趣的可能性......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM