Is it possible to get the name of the function in which this closure is performed?

function MyFunction() { closure = function() { alert('my parent function name is: '/* now what here ? */); } closure(); } MyFunction(); 

The result should be my parent function name is: MyFunction

(To moderators: I don’t know why stackoverflow is stopping me from sending this question, claiming that it does not meet quality standards. Do I have to type extra text so that it can be sent.)

+7
source share
3 answers

It is / is possible, but it is limited. The first limitation, not all Javascript mechanisms support the following template and the second (more dramatic), strict ES5 mode also does not support it.

Some Javascript engines allow you to access the .__parent__ property, which is a reference to the parent scope. It should look like

 alert('my parent is ' + this.__parent__.name ); 

where you will need to call new closure() or give the function a name and use that name instead of this .

However, most implementations eliminate this access for security. As you noticed, you can violate the "omnipotent" security of closure by not being able to access the parent context.


Another way to achieve it is to access arguments.callee.caller , which is also not available in ES5 strict mode. Looks like:

 function MyFunction() { closure = function f() { alert('my parent function name is: ' + arguments.callee.caller.name); } closure(); } MyFunction(); 
+3
source
 function MyFunction() { closure = function() { alert('my parent function name is: ' + arguments.callee.caller.name); } closure(); } MyFunction(); 
+2
source
 function MyFunction() { var functionName = arguments.callee.name, closure = function() { alert('my parent function name is: ' + functionName); } closure(); } MyFunction(); 
+1
source

All Articles