Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 582
Nathan Osman Avatar asked Jan 11 '11 05:01

Nathan Osman


People also ask

Can you assign a function to a variable in JavaScript?

1.1 A regular functionIt is possible to use a function expression and assign it to a regular variable, e.g. const factorial = function(n) {...} .

How do you call a function?

You call the function by typing its name and putting a value in parentheses. This value is sent to the function's parameter. e.g. We call the function firstFunction(“string as it's shown.”);

What is anonymous function in JS?

In JavaScript, an anonymous function is that type of function that has no name or we can say which is without any name. When we create an anonymous function, it is declared without any identifier. It is the difference between a normal function and an anonymous function.


2 Answers

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 
like image 149
amik Avatar answered Sep 22 '22 17:09

amik


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.

like image 31
Christian Mann Avatar answered Sep 23 '22 17:09

Christian Mann