Skip to content

Instantly share code, notes, and snippets.

@irisli
Last active July 18, 2023 14:03
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save irisli/716b6dacd3f151ce2b7e to your computer and use it in GitHub Desktop.
Save irisli/716b6dacd3f151ce2b7e to your computer and use it in GitHub Desktop.
JavaScript get caller in strict mode
"use strict";
var stackTrace = (new Error()).stack; // Only tested in latest FF and Chrome
var callerName = stackTrace.replace(/^Error\s+/, ''); // Sanitize Chrome
callerName = callerName.split("\n")[1]; // 1st item is this, 2nd item is caller
callerName = callerName.replace(/^\s+at Object./, ''); // Sanitize Chrome
callerName = callerName.replace(/ \(.+\)$/, ''); // Sanitize Chrome
callerName = callerName.replace(/\@.+/, ''); // Sanitize Firefox
console.log(callerName)
@istudyatuni
Copy link

istudyatuni commented May 23, 2021

What about this

let stackTrace = (new Error()).stack; // Only tested in latest FF and Chrome
let callerName
try {
    callerName = stackTrace.match(/at Object\.(\w+) \(/)[1]
} catch {
    // Firefox
    callerName = stackTrace.match(/\n\w+@/gm)[0].match(/\w+/)
}

or this

let stackTrace = (new Error()).stack; // Only tested in latest FF and Chrome
let match
try {
	match = stackTrace.match(/at Object\.(\w+) \((\S+)\)/);
	match[1] // throw error if match is null
} catch {
	// Firefox
	match = stackTrace.match(/\n(\w+)@(\S+)/);
}
let [callerName, callerPlace] = [match[1], match[2]]

console.log('Function ' + callerName + ' at ' + callerPlace)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment