javascriptfunctionloggingstrict

How can I access function caller in strict mode at JavaScript


I'm using

I read that function caller is deprecated since ES5(not sure ES5). So I can't use it in strict mode. I don't think disabling strict mode is good idea. Is there any good alternative functions or properties which can be used in strict mode?

Here is a link that i read. There is no alternate in here.

Here is an error message when i try to use caller.

TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them

By the way, this is the first question on stack overflow. I don't know about question rules. I'm glad to if you let me know.

Thank you.

I try to see logs in strict mode. I'd like to see where did it called from. So i access function caller. But i saw an error message.


Solution

  • Seems not possible. But you can get a caller's name and if the caller is accessible from the callee's scope you can eval the caller. Not sure if that's ok to use in production.

    Anyway if you need a caller, pass it as an argument to a callee.
    If you need a caller for a logic (not debugging) that could be a symptom of using a bad design pattern.

    'use strict';
    {
      function fnCaller(){
        fnCallee();
      }
    
      function fnCallee(){
    
        console.log(eval(callerName()));
    
      }
    
      fnCaller();
    }
    <script>
    
    function callerName(){
      try{
        throw new Error;
      }catch(e){
        return e.stack.split('\n')[3].match(/(?<=^\s*at\s*)\S+/)[0];
      }
    }
    
    </script>