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?
It's a shorthand syntax for functions.
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.
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.
No, You can't access let variables outside the block, if you really want to access, declare it outside, which is common scope.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With