Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to PHP's `__FUNCTION__` in JavaScript?

Tags:

javascript

I'm looking for an equivalent to PHP's __FUNCTION__ in JavaScript, to allow me to get the name of the current function. For example:

function foo(){
    console.log(__FUNCTION__); // "foo" would be logged to the console
}

Is there a way to do this in JavaScript? Either with a magic variable similar to __FUNCTION__ or any other workaround? And, if there's not a way to currently achieve this, is it planned?

like image 967
0b10011 Avatar asked Oct 10 '12 16:10

0b10011


People also ask

What doe => mean in JavaScript?

It's a shorthand syntax for functions.

Can I use let in JavaScript?

let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.

Can we store function in a variable in JavaScript?

Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.

Can you access the let variable outside of the block scope?

No, You can't access let variables outside the block, if you really want to access, declare it outside, which is common scope.


1 Answers

You might get a reference to the currently executing function via the callee property of the arguments object. Notice that it is deprecated with ES5.1 strict mode.

From that, you can get the (non-standard) name of the function. Notice that this only works for function declarations and named function expressions (with the known bugs in IE), but not for anonymous functions as object properties:

var myObj = {
    method: function() { // unnamed!
        return arguments.callee.name || "anonymous";
    }
};
myObj.method(); // "anonymous"

I for myself use static strings in debugging / error statements, prepending the whole namespace(s) of the function to easily locate it in the code.

like image 115
Bergi Avatar answered Oct 24 '22 17:10

Bergi