Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find out the caller function in JavaScript when use strict is enabled?

Is it possible to see the callee/caller of a function when use strict is enabled?

'use strict';    function jamie (){      console.info(arguments.callee.caller.name);      //this will output the below error      //uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them  };    function jiminyCricket (){     jamie();  }    jiminyCricket ();
like image 689
Jamie Hutber Avatar asked Apr 11 '15 00:04

Jamie Hutber


People also ask

What is the function caller in JavaScript?

The function. caller property of the JavaScript function object returns the function that invoked the specified function. It returns null if the function “f” was invoked by the top-level code in JavaScript. For functions like strict functions, async functions and generator function this method returns null.

Which of the following method can be used to get the caller of a function?

You can use Function. Caller to get the calling function.

What is the strict mode in JavaScript and how can it be enabled?

The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you can not, for example, use undeclared variables. The numbers in the table specify the first browser version that fully supports the directive. You can use strict mode in all your programs.


1 Answers

For what it's worth, I agree with the comments above. For whatever problem you're trying to solve, there are usually better solutions.

However, just for illustrative purposes, here's one (very ugly) solution:

'use strict'  function jamie (){     var callerName;     try { throw new Error(); }     catch (e) {          var re = /(\w+)@|at (\w+) \(/g, st = e.stack, m;         re.exec(st), m = re.exec(st);         callerName = m[1] || m[2];     }     console.log(callerName); };  function jiminyCricket (){    jamie(); }  jiminyCricket(); // jiminyCricket 

I've only tested this in Chrome, Firefox, and IE11, so your mileage may vary.

like image 121
p.s.w.g Avatar answered Oct 03 '22 12:10

p.s.w.g