Naming an anonymous function

后端 未结 6 1968
心在旅途
心在旅途 2020-12-05 18:33

Is it possible to somehow set a name for anonymous functions?

There is no need to add function names to the namespace for anonymous functions but I would like to avo

6条回答
  •  醉酒成梦
    2020-12-05 18:59

    You could do something like this with arrow functions, it works for me on Node.

    const createTask = ([name, type = 'default']) => {
      const fn = () => { ... }
    
      Object.defineProperty(fn, 'name', {
        value: name,
        configurable: true,
      })
    
      return fn
    }
    

    MDN is somewhat misleading here:

    You cannot change the name of a function, this property is read-only...

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

    This answer provides more details.

提交回复
热议问题