有没有办法在定义为对象一部分的地方获取当前函数名称? 我知道有这种方法可以在其独立函数所在的位置获取函数名称。
函数定义:
function funName(){}
获取函数名:
var myName = arguments.callee.toString();
myName = myName.substr('function '.length);
myName = myName.substr(0, myName.indexOf('('));
但是当它定义为:
时我该如何获取它myobj.prototype.funcName = function(){}
谢谢。
最佳答案
当您使用匿名函数时,我想到的唯一想法是使用辅助函数之类的东西,它
- 抛出一个虚拟错误
- 捕获它
- 解析
堆栈跟踪
- 返回一个包含解析信息的对象
如果它用于调试,这可能是合格的,但我会限制在生产环境中使用它,因为我真的不知道是否抛出错误,解析它们。真是个好主意。
哦,请注意,您不应该使用 arguments.callee
,因为这是不好的做法,甚至在 ECMAScript 5 的
严格模式中也是被禁止的
你可以简单地命名你的函数表达式
Note: You should avoid using arguments.callee() and just give every function (expression) a name.
Warning: The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode.
这就是我第一次尝试时想到的我只在最新的 IE
Firefox
Chrome
上测试过,所以你可能需要调整代码
var stackTest = function () {
console.log(getStack(0).fn); //stackTest
}
function getStack(n) {
var stacks = [];
try {
throw new Error("Test")
} catch (e) {
var stack = e.stack.split("\n");
for (var i = 0, j = stack.length; i < j; i++) {
var current = stack[i].match(/^(?:\s*at? ?)?(.+?)(?:@| )\(?(.*?):[^\/](\d*):?(\d*)?/)
if (current == null) {
continue
}
var entry = {
fn: current[1] || "anonymous",
file: current[2] || "unknown",
line: ~~current[3],
column: ~~current[4],
time: new Date().getTime()
}
if ("getStack" !== entry.fn) stacks.push(entry);
}
} finally {
return "number" === typeof n ? stacks[n] : stacks;
}
}
stackTest();
这是一个示例输出,使用对象的原型(prototype)函数
function test() {}
test.prototype.anotherTest = function () {
console.log(getStack(0).fn);
//Chrome: "test.anotherTest"
//Firefox: "test.prototype.anotherTest"
//IE: "anotherTest"
}
var instance = new test();
instance.anotherTest();
还有关于 JSBin 的示例:
关于javascript - 如何在定义为对象一部分的地方获取当前函数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15493437/