开发者

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

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 supe开发者_如何学Crfluous text to be allowed to send this.)


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();


function MyFunction() {
  closure = function() {
    alert('my parent function name is: ' + arguments.callee.caller.name);
  }
  closure();
}
MyFunction();


function MyFunction() {
    var functionName = arguments.callee.name,
    closure = function() {
        alert('my parent function name is: ' + functionName);
    }
    closure();
}
MyFunction();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜