繁体   English   中英

获取包含该函数的匿名变量的名称

[英]Get the name of the anonymous variable that contains the function

我有这些功能

function getCallingFunctionName() {
    alert(arguments.callee.caller.name.toString();
}

var bob = function() {
    ...
    getCallingFunctionName();
}

运行代码时,提醒的值是返回空字符串。 我需要回来

 bob

我不能改变原来的功能(即时通讯处理具有数千个功能的大型项目等。

var bob = function bob() {
    ...
    getCallingFunctionName();
}

任何人有任何其他想法? 它并不重要但基本上可以帮助调试。

如果您尝试执行以下操作,该怎么办:

function getCallingFunctionName() {
    try {
        throw new Error();
    }
    catch(e) {
        console.log(e);
    }
}

var bob = function() {
    getCallingFunctionName();
}

它会给你这样的东西:

Error
    at getCallingFunctionName (<anonymous>:4:15)
    at bob (<anonymous>:12:5)
    at <anonymous>:2:1
    at Object.InjectedScript._evaluateOn (<anonymous>:581:39)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:540:52)
    at Object.InjectedScript.evaluate (<anonymous>:459:21) 

您可以将其用于您的目的,即提取功能名称。 唯一可悲的是,IE从版本10开始支持Error.stack

这是一种方法,需要一点额外的努力/代码,但也许它适合你:

var cache = {};

var bob = function () {
    getCallingFunctionName();
}

function getCallingFunctionName() {
    alert(cache[arguments.callee.caller.toString()]);
}

cache[bob.toString()] = "bob";

bob(); //bob

所以你基本上是缓存函数字符串表示(这是完整的函数体)并将其用作实际函数名的键。 之后您可以再次使用func.toString()来访问该名称。 当然,这要求您没有两个具有完全相同主体的功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM