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?
You might get a reference to the currently executing function via the
calleeproperty of theargumentsobject. Notice that it is deprecated with ES5.1 strict mode.From that, you can get the (non-standard)
nameof 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: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.