0

Is there a way to automatically know who called a specific function in JS?

Let's say I have this code:

function1() {
function2();
}

function2() {
console.log('the function who called me is ...' + <magic code here>);
}

When function1 calls function2, is there any magic way for function2 to know that function1 called it, without passing any additional parameters?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
delphirules
  • 6,443
  • 17
  • 59
  • 108

1 Answers1

-1

You can use function2.caller. Using caller property gives you the detail of the function that invoked it. And further use name property to get the name of the calling function.

function function1(){
  function2();
}

function function2() {
  console.log('called by function' + function2.caller.name);
  console.log('the function who called me is ...');
}

function1();
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62