53

が有効になっているときに、関数の呼び出し先/呼び出し元を確認することuse strictはできますか?

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

4

5 に答える 5

51

その価値については、上記のコメントに同意します。解決しようとしている問題が何であれ、通常はより良い解決策があります。

ただし、説明目的のためだけに、1 つの (非常に醜い) ソリューションを次に示します。

'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 でのみこれをテストしたので、走行距離は異なる場合があります。

于 2015-04-11T00:17:01.323 に答える