0

I have created a function dynamically via Function constructor. Now I want to get the name of the function within itself. How can this be possible?

var myFunc = new Function("arg", "// want the name here")

I can call the function using myFunc(arg) but the name does not gets printed using arguments.callee.name

Update: Is there any way to get the reference atleast i.e. something like

myFunc instanceof <something>...
Rusheel Jain
  • 843
  • 6
  • 20

1 Answers1

2

Functions created using the Function constructor are anonymous, that's why .name is empty. If for some reasons you need a named function, have a look at Is there any non-eval way to create a function with a runtime-determined name?.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • is there any way to atleast get the self reference. Say for example, myFunc instanceof something.. – Rusheel Jain Apr 24 '16 at 21:11
  • From inside the function? No, not unless `myFunc` is global. `arguments.callee` is deprecated for good reason. What do you need it for? – Bergi Apr 24 '16 at 21:14
  • I have a repeating-callback function that gets registered to a library function and is then called via this library. So I can change the name of the callback function but not the parameters passed. But for some reasons I want to know have a reference of this callback when it get called. And yes 'myFunc' can be made global – Rusheel Jain Apr 24 '16 at 21:32
  • Why are you creating that function using the `Function` constructor at all? How many of these callbacks do you need? – Bergi Apr 24 '16 at 21:33
  • the number of callbacks would be decided at runtime. Max 7-10 maybe would be required. so say there is callback1 -> do ABC. Push result to arr1 callback2 -> do same ABC. BUT push result to arr2 – Rusheel Jain Apr 24 '16 at 21:35
  • Sounds like a simple closure should suffice. Why are you using `new Function`? – Bergi Apr 24 '16 at 21:40
  • could you provide an example please?. since I am unable to understand how pass this '1','2' '3' etc values into the closure (parameters are passed via library function) – Rusheel Jain Apr 24 '16 at 21:42
  • The closure can both access its paramters and the variables in its scope. Maybe you want to ask another question with your actual code so that we can provide an actual solution – Bergi Apr 24 '16 at 22:00
  • Thanks for the hint. I was able to solve the issue via closure only. Thanks a ton!! – Rusheel Jain Apr 24 '16 at 22:01