0

How can I access the name of a running function that is attached to a prototype?

See my best attempt below. It outputs an empty string.

Client.prototype.setAllMain = function() {
    console.log(this.setAllMain.name);
}
user1283776
  • 19,640
  • 49
  • 136
  • 276
  • https://stackoverflow.com/questions/2648293/how-to-get-the-function-name-from-within-that-function – Rafael Herscovici Jan 30 '19 at 09:41
  • 3
    If the function is not anonymous, `.name` should work. setAllMain is written as an anonymous function though and will not have a name. Why do you need the function name though? Since needing the function name at runtime is usually a sign of other problems – Shilly Jan 30 '19 at 09:41
  • 1
    What is `this.getArcs`? – Bergi Jan 30 '19 at 09:42
  • @Shilly a hackish way would be to throw error and loop through stacktrace to get first named function. However, it will be an ugly way – Rajesh Jan 30 '19 at 09:46
  • @Bergi: It was a typo, fixed now – user1283776 Jan 30 '19 at 09:48
  • 2
    I'd prefer `Client.prototype.setAllMain = function setAllMain () { ... };`, so that it has a proper name and .name will work. Seems more sensible than parsing a stack trace or using arguments.calle, which won't work in strict mode. – Shilly Jan 30 '19 at 09:49
  • 1
    @user1283776 Ah ok. But I don't get it, if you know that you want to get the property name of `this.setAllMain`, why not just write `"setAllMain"`? – Bergi Jan 30 '19 at 13:21
  • @Bergi: Thanks for asking. I must admit that there was no good reason really. I just couldn't figure out why my various attempts were not working and wanted to understand what was wrong. I think Shilly solved the problem. – user1283776 Jan 30 '19 at 13:32

0 Answers0