我可以在JavaScript中获取当前运行的函数的名称吗?

时间:2009-06-18 15:10:34

标签: javascript jquery dojo

是否可以这样做:

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

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

20 个答案:

答案 0 :(得分:168)

您应该可以使用arguments.callee来获取它。

你可能不得不解析名称,因为它可能包含一些额外的垃圾。但是,在某些实现中,您只需使用arguments.callee.name获取名称。

解析:

function DisplayMyName() 
{
   var myName = arguments.callee.toString();
   myName = myName.substr('function '.length);
   myName = myName.substr(0, myName.indexOf('('));

   alert(myName);
}
  

来源:Javascript - get current function name

答案 1 :(得分:60)

对于非匿名函数

function foo()
{ 
    alert(arguments.callee.name)
}

但是在错误处理程序的情况下,结果将是错误处理函数的名称,不是吗?

答案 2 :(得分:26)

您需要的一切都很简单。 创建功能:

 <img [routerLink]="['our-products']" fragment="element" data-src="../../assets/img/product-logos/product-logo.svg" alt="Product Logo">

在您需要之后,您只需使用:

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

答案 3 :(得分:25)

根据MDN

  

警告:第5版ECMAScript(ES5)禁止在严格模式下使用arguments.callee()。避免使用arguments.callee()通过为函数表达式赋予名称或使用函数必须调用自身的函数声明。

如上所述,如果您的脚本使用&#34;严格模式&#34;,则仅适用 。这主要是出于安全原因,遗憾的是目前还没有替代方案。

答案 4 :(得分:21)

这应该这样做:

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

对于来电者,只需使用caller.toString()

答案 5 :(得分:10)

这必须属于“世界上最丑陋的黑客”的范畴,但是你走了。

首先,打印当前功能的名称(如在其他答案中一样)似乎对我有用,因为你已经知道这个功能是什么了!

但是,查找调用函数的名称对跟踪函数非常有用。这是一个正则表达式,但使用indexOf将快3倍左右:

function getFunctionName() {
    var re = /function (.*?)\(/
    var s = getFunctionName.caller.toString();
    var m = re.exec( s )
    return m[1];
}

function me() {
    console.log( getFunctionName() );
}

me();

答案 6 :(得分:8)

这是一种可行的方式:

export function getFunctionCallerName (){
  // gets the text between whitespace for second part of stacktrace
  return (new Error()).stack.match(/at (\S+)/g)[1].slice(3);
}

然后在你的测试中:

import { expect } from 'chai';
import { getFunctionCallerName } from '../../../lib/util/functions';

describe('Testing caller name', () => {

    it('should return the name of the function', () => {
      function getThisName(){
        return getFunctionCallerName();
      }

      const functionName = getThisName();

      expect(functionName).to.equal('getThisName');
    });

  it('should work with an anonymous function', () => {


    const anonymousFn = function (){
      return getFunctionCallerName();
    };

    const functionName = anonymousFn();

    expect(functionName).to.equal('anonymousFn');
  });

  it('should work with an anonymous function', () => {
    const fnName = (function (){
      return getFunctionCallerName();
    })();

    expect(/\/util\/functions\.js/.test(fnName)).to.eql(true);
  });

});

请注意,第三个测试仅在测试位于/ util / functions

时才有效

答案 7 :(得分:3)

另一个用例可能是在运行时绑定的事件调度程序:

MyClass = function () {
  this.events = {};

  // Fire up an event (most probably from inside an instance method)
  this.OnFirstRun();

  // Fire up other event (most probably from inside an instance method)
  this.OnLastRun();

}

MyClass.prototype.dispatchEvents = function () {
  var EventStack=this.events[GetFunctionName()], i=EventStack.length-1;

  do EventStack[i]();
  while (i--);
}

MyClass.prototype.setEvent = function (event, callback) {
  this.events[event] = [];
  this.events[event].push(callback);
  this["On"+event] = this.dispatchEvents;
}

MyObject = new MyClass();
MyObject.setEvent ("FirstRun", somecallback);
MyObject.setEvent ("FirstRun", someothercallback);
MyObject.setEvent ("LastRun", yetanothercallback);

这里的优点是调度程序可以很容易地重用,并且不必将调度队列作为参数接收,而是隐含了调用名称...

最后,这里给出的一般情况是“使用函数名作为参数,因此您不必明确地传递它”,这在许多情况下可能很有用,例如jquery animate()可选回调,或超时/间隔回调,(即你只传递一个功能名称)。

答案 8 :(得分:2)

以下代码段中的getMyName函数返回调用函数的名称。这是一个黑客,依赖于non-standard功能:Error.prototype.stack。请注意,Error.prototype.stack返回的字符串格式在不同引擎中的实现方式不同,因此这可能无法在任何地方使用:

function getMyName() {
  var e = new Error('dummy');
  var stack = e.stack
                .split('\n')[2]
                // " at functionName ( ..." => "functionName"
                .replace(/^\s+at\s+(.+?)\s.+/g, '$1' );
                return stack
}

function foo(){
  return getMyName()
}

function bar() {
  return foo()
}

console.log(bar())

关于其他解决方案:arguments.callee is not allowed in strict modeFunction.prototype.callernon-standard and not allowed in strict mode

答案 9 :(得分:1)

由于您编写了一个名为foo的函数,并且您知道它位于myfile.js中,为什么需要动态获取此信息?

话虽如此,你可以在函数中使用arguments.callee.toString()(这是整个函数的字符串表示),并且正则表达函数名的值。

这是一个会吐出自己名字的函数:

function foo() {
    re = /^function\s+([^(]+)/
    alert(re.exec(arguments.callee.toString())[1]);             
}

答案 10 :(得分:1)

自从问了这个问题以来,当前函数的名称及其获取方式似乎在过去10年中已经发生了变化。

现在,不是一个专业的Web开发人员,他不知道所有存在的浏览器的所有历史,这是它在2019年chrome浏览器中对我的作用:

function callerName() {
    return callerName.caller.name;
}
function foo() {
    let myname = callerName();
    // do something with it...
}

其他一些答案遇到了一些严格的javascript代码等问题。

答案 11 :(得分:1)

在这个答案中可以找到更新的答案: https://stackoverflow.com/a/2161470/632495

并且,如果您不想点击:

function test() {
  var z = arguments.callee.name;
  console.log(z);
}

答案 12 :(得分:1)

2016年的信息是实际的。

功能声明的结果

歌剧中的结果

>>> (function func11 (){
...     console.log(
...         'Function name:',
...         arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
... })();
... 
... (function func12 (){
...     console.log('Function name:', arguments.callee.name)
... })();
Function name:, func11
Function name:, func12

Chrome中的结果

(function func11 (){
    console.log(
        'Function name:',
        arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
})();

(function func12 (){
    console.log('Function name:', arguments.callee.name)
})();
Function name: func11
Function name: func12

结果在NodeJS

> (function func11 (){
...     console.log(
.....         'Function name:',
.....         arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
... })();
Function name: func11
undefined
> (function func12 (){
...     console.log('Function name:', arguments.callee.name)
... })();
Function name: func12

在Firefox中不起作用。在IE和Edge上未经测试。

函数表达式的结果

结果在NodeJS

> var func11 = function(){
...     console.log('Function name:', arguments.callee.name)
... }; func11();
Function name: func11

Chrome中的结果

var func11 = function(){
    console.log('Function name:', arguments.callee.name)
}; func11();
Function name: func11

在Firefox,Opera中不起作用。在IE和Edge上未经测试。

注意:

  1. 匿名功能没有意义检查。
  2. 测试环境
  3. ~ $ google-chrome --version
    Google Chrome 53.0.2785.116           
    ~ $ opera --version
    Opera 12.16 Build 1860 for Linux x86_64.
    ~ $ firefox --version
    Mozilla Firefox 49.0
    ~ $ node
    node    nodejs  
    ~ $ nodejs --version
    v6.8.1
    ~ $ uname -a
    Linux wlysenko-Aspire 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
    

答案 13 :(得分:0)

由于arguments.callee.name 是非标准的,并且在ECMAScript 5 严格模式(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee) 中是被禁止的,因此动态检索函数名称[如魔术变量] 的一个简单解决方案是使用作用域变量,并且Function.name 属性。

{
  function foo() {
    alert (a.name);
  }; let a = foo
}
{
  function foo2() {
    alert(a.name)
  }; let a = foo2
};
foo();//logs foo
foo2();//logs foo2

注意:嵌套函数不再是源元素,因此不会被提升。此外,这种技术不能用于匿名函数。

答案 14 :(得分:0)

这是Igor Ostroumov's答案的一种形式:

如果要将其用作参数的默认值,则需要考虑对“调用者”进行第二级调用:

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

这将动态允许在多个功能中实现可重用的实现。

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

function bar(myFunctionName = getFunctionsNameThatCalledThisFunction())
{ 
  alert(myFunctionName);
}

// pops-up "foo"
function foo()
{
  bar();
}

function crow()
{
  bar();
}

foo();
crow();

如果您也想要文件名,以下是使用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();
}

答案 15 :(得分:0)

(function f() {
    console.log(f.name);  //logs f
})();

打字稿变体:

function f1() {} 
function f2(f:Function) {
   console.log(f.name);
}

f2(f1);  //Logs f1

仅在符合ES6 / ES2015的引擎中提供注释。 https://docs.branch.io/pages/organic-search/firebase/#overview

答案 16 :(得分:0)

这是一个班轮:

    arguments.callee.toString().split('\n')[0].substr('function '.length).replace(/\(.*/, "").replace('\r', '')

像这样:

    function logChanges() {
      let whoami = arguments.callee.toString().split('\n')[0].substr('function '.length).replace(/\(.*/, "").replace('\r', '');
      console.log(whoami + ': just getting started.');
    }

答案 17 :(得分:0)

我在这里看到的少数回应的组合。 (经过FF,Chrome,IE11测试)

function functionName() 
{
   var myName = functionName.caller.toString();
   myName = myName.substr('function '.length);
   myName = myName.substr(0, myName.indexOf('('));
   return myName;
}

function randomFunction(){
    var proof = "This proves that I found the name '" + functionName() + "'";
    alert(proof);
}

调用randomFunction()将警告包含函数名称的字符串。

JS小提琴演示:http://jsfiddle.net/mjgqfhbe/

答案 18 :(得分:-2)

尝试:

alert(arguments.callee.toString());

答案 19 :(得分:-7)

答案很简短:alert(arguments.callee.name);