Quite a while back I wrote about a Me
function for C#. I used to have an equivalent in JavaScript ES3. It used the now-deprecated arguments
vector, which had to be passed in on the call:
function Me(a) {
return a.callee.toString().split(" ")[1].split("(")[0].trim();
}
// example usage.
function foo() {
Logger.log("[%s] We are in function %s", Me(arguments), Me(arguments));
}
I recently discovered a way that works for more recent JavaScripts including Google Apps Script. I expect it is not the most performant and should not be used in a Production environment. It's proving very helpful in Development.
The code below is TypeScript. Remove the : string
and the exclamation mark after stack
and you should have working JavaScript.
function Me() : string {
const e = new Error();
const frame = e.stack!.split("\n")[2];
const functionName = frame.split(" ")[5];
return functionName;
}
The function can be used for logging and who knows what else:
function foo() {
Logger.log("[%s] We are in function %s", Me(), Me());
}
Top comments (0)