是否有可能获得给定闭包运行的函数名称?

rsk*_*k82 7 javascript

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

结果应该是 my parent function name is: MyFunction

(对于主持人:我不知道为什么stackoverflow阻止我发送这个问题声称它不符合质量标准.我是否必须输入一些多余的文本才能发送它.)

jAn*_*ndy 3

这是可能,但它受到限制。第一个限制,并非所有 Javascript 引擎都支持以下模式,第二个(更戏剧性),ES5 严格模式也不支持它。

某些 Javascript 引擎允许您访问.__parent__作为对父作用域的引用的属性。那应该看起来像

alert('my parent is ' + this.__parent__.name );
Run Code Online (Sandbox Code Playgroud)

您必须调用new closure(),或者为函数命名并使用该名称而不是this

然而,出于安全考虑,大多数实现都删除了该访问权限。正如您可能注意到的,您可以通过访问父上下文来破坏“全能”的闭包安全性。


另一种实现方法是访问,这在ES5 严格模式arguments.callee.caller下也是无法访问的。好像:

function MyFunction() {
  closure = function f() {
    alert('my parent function name is: ' +  arguments.callee.caller.name);
  }
 closure();
}
MyFunction();
Run Code Online (Sandbox Code Playgroud)