启用use strict后,如何查找JavaScript中的调用程序函数? [英] How do you find out the caller function in JavaScript when use strict is enabled?

查看:43
本文介绍了启用use strict后,如何查找JavaScript中的调用程序函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

启用use strict时是否可以查看某个函数的被调用者/调用者?

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 ();

推荐答案

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

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.

这篇关于启用use strict后,如何查找JavaScript中的调用程序函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆