有可能这样做吗:

myfile.js:
function foo() {
    alert(<my-function-name>);
    // pops-up "foo"
    // or even better: "myfile.js : foo"
}

我的堆栈中有Dojo和jQuery框架,所以如果它们中的任何一个使工作更容易,都可以使用它们。


当前回答

这是伊戈尔·奥斯特鲁莫夫回答的一个变体:

如果你想使用它作为参数的默认值,你需要考虑对'caller'的二级调用:

function getFunctionsNameThatCalledThisFunction()
{
  return getFunctionsNameThatCalledThisFunction.caller.caller.name;
}

这将动态地允许多个函数中的可重用实现。

getFunctionsNameThatCalledThisFunction()函数 { 返回getFunctionsNameThatCalledThisFunction.caller.caller.name; } (myFunctionName = getFunctionsNameThatCalledThisFunction()) { 警报(myFunctionName); } //弹出"foo" 函数foo () { 酒吧(); } 乌鸦()函数 { 酒吧(); } foo (); 乌鸦();

如果你也想要文件名,这里是使用F-3000在另一个问题上的答案的解决方案:

function getCurrentFileName()
{
  let currentFilePath = document.scripts[document.scripts.length-1].src 
  let fileName = currentFilePath.split('/').pop() // formatted to the OP's preference

  return fileName 
}

function bar(fileName = getCurrentFileName(),  myFunctionName = getFunctionsNameThatCalledThisFunction())
{
  alert(fileName + ' : ' + myFunctionName);
}

// or even better: "myfile.js : foo"
function foo()
{
  bar();
}

其他回答

这应该做到:

var fn = arguments.callee.toString().match(/function\s+([^\s\(]+)/);
alert(fn[1]);

对于调用者,只需使用caller. tostring()。

根据MDN

警告:ECMAScript (ES5)第5版禁止在严格模式下使用arguments.callee()。避免使用arguments.callee(),方法是给函数表达式一个名称,或者在函数必须调用自身的地方使用函数声明。

如上所述,这只适用于你的脚本使用“严格模式”。这主要是出于安全考虑,遗憾的是目前还没有替代方案。

这是伊戈尔·奥斯特鲁莫夫回答的一个变体:

如果你想使用它作为参数的默认值,你需要考虑对'caller'的二级调用:

function getFunctionsNameThatCalledThisFunction()
{
  return getFunctionsNameThatCalledThisFunction.caller.caller.name;
}

这将动态地允许多个函数中的可重用实现。

getFunctionsNameThatCalledThisFunction()函数 { 返回getFunctionsNameThatCalledThisFunction.caller.caller.name; } (myFunctionName = getFunctionsNameThatCalledThisFunction()) { 警报(myFunctionName); } //弹出"foo" 函数foo () { 酒吧(); } 乌鸦()函数 { 酒吧(); } foo (); 乌鸦();

如果你也想要文件名,这里是使用F-3000在另一个问题上的答案的解决方案:

function getCurrentFileName()
{
  let currentFilePath = document.scripts[document.scripts.length-1].src 
  let fileName = currentFilePath.split('/').pop() // formatted to the OP's preference

  return fileName 
}

function bar(fileName = getCurrentFileName(),  myFunctionName = getFunctionsNameThatCalledThisFunction())
{
  alert(fileName + ' : ' + myFunctionName);
}

// or even better: "myfile.js : foo"
function foo()
{
  bar();
}

下面代码段中的getMyName函数返回调用函数的名称。这是一个黑客,依赖于非标准的特性:Error.prototype.stack。注意,由Error.prototype.stack返回的字符串格式在不同的引擎中实现是不同的,所以这可能不会在任何地方都适用:

函数getMyName() { var e = new错误('dummy'); Var stack = e.stack .split(“\ n”)[2] // " at functionName(…)"“= >”functionName .replace (/ ^ \ s + \ s + (+ ?) \ s。+/g, '$1'); 返回栈 } 函数foo () { 返回getMyName () } 功能栏(){ 返回foo () } console.log (bar ())

关于其他解决方案:争论。严格模式下不允许使用callee,严格模式下不允许使用Function.prototype.calleris非标准的。

你所需要的很简单。 创建函数:

function getFuncName() {
   return getFuncName.caller.name
}

在此之后,无论何时你需要,你只需使用:

function foo() { 
  console.log(getFuncName())
}

foo() 
// Logs: "foo"