Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to get function name in which given closure is running?

Tags:

javascript

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

Result should be my parent function name is: MyFunction

(To moderators: I do not know why stackoverflow is preventing me from sending this question claiming it doesn't meet quality standards. Do I must type some superfluous text to be allowed to send this.)

like image 502
rsk82 Avatar asked Aug 16 '11 12:08

rsk82


People also ask

When closure is created?

The use of closures is associated with languages where functions are first-class objects, in which functions can be returned as results from higher-order functions, or passed as arguments to other function calls; if functions with free variables are first-class, then returning one creates a closure.

Are C functions closures?

Although C was created two decades after Lisp, it nonetheless lacks support for closures.

What could be the alternative to closure?

Webpack, Babel, UglifyJS, and TypeScript are the most popular alternatives and competitors to Closure Compiler.


2 Answers

That is/was possible, but it is restricted. First restriction, not all Javascript engines support the following pattern and second (more dramatic), ES5 strict mode does not support it either.

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

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

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

However, most implementations removed that access for security concerns. As you may noticed, you're able to breach the 'allmighty' closure security by beeing able to access the parent context.


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

function MyFunction() {
  closure = function f() {
    alert('my parent function name is: ' +  arguments.callee.caller.name);
  }
 closure();
}
MyFunction();
like image 116
jAndy Avatar answered Oct 17 '22 11:10

jAndy


function MyFunction() {
  closure = function() {
    alert('my parent function name is: ' + arguments.callee.caller.name);
  }
  closure();
}
MyFunction();
like image 24
mVChr Avatar answered Oct 17 '22 13:10

mVChr