且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

启用use strict后,如何查找JavaScript中的调用程序函数?

更新时间:2023-12-05 23:50:46

对于它的价值,我同意上面的评论.对于您要解决的任何问题,通常都有更好的解决方案.

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

我只在Chrome,Firefox和IE11上对此进行了测试,因此您的学习里程可能会有所不同.

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