Javascript 有没有办法从当前函数中获取当前函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4654388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:28:42  来源:igfitidea点击:

Is there a way to get the current function from within the current function?

javascriptfunction

提问by Nathan Osman

Sorry for the really weird title, but here's what I'm trying to do:

很抱歉这个标题很奇怪,但这是我想要做的:

var f1 = function (param1, param2) {

    // Is there a way to get an object that is ‘f1'
    // (the current function)?

};

As you can see, I would like to access the current function from within an anonymous function.

如您所见,我想从匿名函数中访问当前函数。

Is this possible?

这可能吗?

采纳答案by Christian Mann

Yes – arguments.calleeis the current function.

是 -arguments.callee是当前功能。

NOTE: This is deprecated in ECMAScript 5, and may cause a performance hit for tail-call recursion and the like. However, it does work in most major browsers.

注意:这在 ECMAScript 5 中已被弃用,并且可能会导致尾调用递归等性能下降。但是,它确实适用于大多数主要浏览器。

In your case, f1will also work.

在您的情况下,f1也将起作用。

回答by amik

Name it.

命名它。

var f1 = function fOne() {
    console.log(fOne); //fOne is reference to this function
}
console.log(fOne); //undefined - this is good, fOne does not pollute global context

回答by David Tang

You can access it with f1since the function will have been assigned to the variable f1beforeit is called:

您可以使用它来访问它,f1因为该函数将f1调用之前分配给变量:

var f1 = function () {
    f1(); // Is valid
};

f1(); // The function is called at a later stage

回答by mjudd

@amik Mentioned this, but if you write your functions as arrow functions it seems a little nicer to me:

@amik 提到了这一点,但是如果您将函数编写为箭头函数,对我来说似乎更好一些:

const someFunction = () => { 
  console.log(someFunction); // will log this function reference
  return someFunction;
}