[英]Get the name of the anonymous variable that contains the function
I have the functions 我有这些功能
function getCallingFunctionName() {
alert(arguments.callee.caller.name.toString();
}
var bob = function() {
...
getCallingFunctionName();
}
When the code is run the value alerted is an empty string is returned. 运行代码时,提醒的值是返回空字符串。 I need to return 我需要回来
bob
I CANNOT change the original functions (im dealing with a large project with thousands of functions etc. 我不能改变原来的功能(即时通讯处理具有数千个功能的大型项目等。
var bob = function bob() {
...
getCallingFunctionName();
}
Any one got any other ideas ? 任何人有任何其他想法? Its not critical to have but basically to help with debugging. 它并不重要但基本上可以帮助调试。
What if you try to do something like this: 如果您尝试执行以下操作,该怎么办:
function getCallingFunctionName() {
try {
throw new Error();
}
catch(e) {
console.log(e);
}
}
var bob = function() {
getCallingFunctionName();
}
It will give you something like this: 它会给你这样的东西:
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)
which you can use for your purpose, ie to extract function name. 您可以将其用于您的目的,即提取功能名称。 The only sad thing is that IE supports Error.stack starting from version 10. 唯一可悲的是,IE从版本10开始支持Error.stack 。
Here is a way, that requires a little extra effort/code, but maybe it suits you: 这是一种方法,需要一点额外的努力/代码,但也许它适合你:
var cache = {};
var bob = function () {
getCallingFunctionName();
}
function getCallingFunctionName() {
alert(cache[arguments.callee.caller.toString()]);
}
cache[bob.toString()] = "bob";
bob(); //bob
So you are basically caching the function string representation (which is the complete function body) and using it as a key for the actual function name. 所以你基本上是缓存函数字符串表示(这是完整的函数体)并将其用作实际函数名的键。 Afterwards you can access the name, using again only func.toString()
. 之后您可以再次使用func.toString()
来访问该名称。 Of course, this requires that you don't have two functions who have the exact same body. 当然,这要求您没有两个具有完全相同主体的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.