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

后端 未结 5 1433
谎友^
谎友^ 2020-12-01 04:53

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

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 05:49

    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.

提交回复
热议问题