有可能这样做吗:
myfile.js:
function foo() {
alert(<my-function-name>);
// pops-up "foo"
// or even better: "myfile.js : foo"
}
我的堆栈中有Dojo和jQuery框架,所以如果它们中的任何一个使工作更容易,都可以使用它们。
有可能这样做吗:
myfile.js:
function foo() {
alert(<my-function-name>);
// pops-up "foo"
// or even better: "myfile.js : foo"
}
我的堆栈中有Dojo和jQuery框架,所以如果它们中的任何一个使工作更容易,都可以使用它们。
当前回答
这里有一句话:
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.');
}
其他回答
这应该做到:
var fn = arguments.callee.toString().match(/function\s+([^\s\(]+)/);
alert(fn[1]);
对于调用者,只需使用caller. tostring()。
对于非匿名函数
function foo()
{
alert(arguments.callee.name)
}
但在错误处理程序的情况下结果应该是错误处理程序函数的名称,不是吗?
这个问题的最新答案可以在这个答案中找到: https://stackoverflow.com/a/2161470/632495
如果你不想点击:
function test() {
var z = arguments.callee.name;
console.log(z);
}
既然你写了一个名为foo的函数,你知道它在myfile.js中,为什么你需要动态地获取这个信息?
也就是说,你可以在函数内部使用arguments.callee.toString()(这是整个函数的字符串表示),并regex出函数名的值。
下面是一个会吐出自己名字的函数:
function foo() {
re = /^function\s+([^(]+)/
alert(re.exec(arguments.callee.toString())[1]);
}
答案很简单:alert(arguments.callee.name);