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

JavascriptFunction

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Yes – arguments.callee is the current function.

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.

In your case, f1 will also work.

Solution 3 - Javascript

You can access it with f1 since the function will have been assigned to the variable f1 before it is called:

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathan OsmanView Question on Stackoverflow
Solution 1 - JavascriptamikView Answer on Stackoverflow
Solution 2 - JavascriptChristian MannView Answer on Stackoverflow
Solution 3 - JavascriptDavid TangView Answer on Stackoverflow