[英]How can I get the name of function inside a JavaScript function?
怎样才能知道我所在的函数的名称?
下面的代码提醒“对象”。 但我需要知道如何提醒“外部”。
function Outer(){
alert(typeof this);
}
这将有效:
function test() {
var z = arguments.callee.name;
console.log(z);
}
我认为你可以这样做:
var name = arguments.callee.toString();
有关这方面的更多信息,请查看本文 。
function callTaker(a,b,c,d,e){
// arguments properties
console.log(arguments);
console.log(arguments.length);
console.log(arguments.callee);
console.log(arguments[1]);
// Function properties
console.log(callTaker.length);
console.log(callTaker.caller);
console.log(arguments.callee.caller);
console.log(arguments.callee.caller.caller);
console.log(callTaker.name);
console.log(callTaker.constructor);
}
function callMaker(){
callTaker("foo","bar",this,document);
}
function init(){
callMaker();
}
从ES6开始,您可以使用Function.prototype.name
。 这具有使用箭头函数的额外好处,因为它们没有自己的参数对象。
function logFuncName() {
console.log(logFuncName.name);
}
const logFuncName2 = () => {
console.log(logFuncName2.name);
};
我花了一段时间才弄明白这一点,所以试着让像我这样的新手说清楚。
这种方法曾经有效,但现在在 ES6 严格模式下它会失败。 不要使用方法 1。
//approach 1 - don't use
let functionName = arguments.callee.name;
console.log(functionName);
这种方法适用于最新版本的 Javascript,在严格模式下不会失败。 使用方法 2。有 2 个步骤。
步骤 1 - 创建一个函数,该函数使用 caller.name 返回调用它的函数的名称。 将此函数添加到您的代码中:
function getFuncName() {
return getFuncName.caller.name
}
第 2 步 - 当您需要代码当前所在函数的名称时调用您的函数。
function iWantThisName() {
console.log(getFuncName())
}
iWantThisName()
// Logs: "iWantThisName"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.