有可能这样做吗:
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对象是一个局部变量,可在所有非箭头函数中使用。 可以使用函数的arguments对象来引用函数内部的参数。 它对调用函数的每个参数都有条目,第一个条目的索引为0。
所以你基本上可以使用arguments。callee。name但是在命名函数内部,像这样:
function i_have_a_name() {
console.log(`My name is:`, arguments.callee.name)
}
> i_have_a_name()
My name is: i_have_a_name
不幸的是,它不能在箭头函数中使用:
const i_have_a_name = () => {
console.log(`My name is:`, arguments.callee.name)
}
> i_have_a_name()
Uncaught ReferenceError: arguments is not defined
at i_have_a_name (REPL3:2:32)
来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
其他回答
(function f() {
console.log(f.name); //logs f
})();
打印稿变化:
function f1() {}
function f2(f:Function) {
console.log(f.name);
}
f2(f1); //Logs f1
注意仅适用于ES6/ES2015兼容引擎。更多信息请参见
在ES5及以上版本中,无法访问该信息。
在旧版本的JS中,你可以使用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);
}
获取当前函数名。
Try:
alert(arguments.callee.toString());
这是伊戈尔·奥斯特鲁莫夫回答的一个变体:
如果你想使用它作为参数的默认值,你需要考虑对'caller'的二级调用:
function getFunctionsNameThatCalledThisFunction()
{
return getFunctionsNameThatCalledThisFunction.caller.caller.name;
}
这将动态地允许多个函数中的可重用实现。
getFunctionsNameThatCalledThisFunction()函数 { 返回getFunctionsNameThatCalledThisFunction.caller.caller.name; } (myFunctionName = getFunctionsNameThatCalledThisFunction()) { 警报(myFunctionName); } //弹出"foo" 函数foo () { 酒吧(); } 乌鸦()函数 { 酒吧(); } foo (); 乌鸦();
如果你也想要文件名,这里是使用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();
}
答案很简单:alert(arguments.callee.name);