How to get caller from strict mode?

戏子无情 提交于 2019-12-17 19:12:31

问题


Strict and non-strict code can be mixed. But you can't use caller even if the call to it is not in strict code. Does anybody know any workaround?

I tried this:

(function strict(){
    "use strict";
    nonStrict();//ok
    nonStrictCaller();//error :(
})();

function nonStrict(){
    return 011;//Octal literals are not allowed in strict mode
}

function nonStrictCaller(){
    return nonStrictCaller.caller;
}

回答1:


Here's an evil hack that only works in V8. The 140 bytes version:

function x(a,b,c){function d(e,f){d=f}c=(b=Error)[a='prepareStackTrace'];b.captureStackTrace(b[a]=d,x);d.stack;b[a]=c;return d}

And the less cryptic version

if ('captureStackTrace' in Error) {
  void function(){
    function prepare(e, callsites){
      return callsites;
    }

    function stack(f){
      var e = {};
      var oldPrepare = Error.prepareStackTrace;
      Error.prepareStackTrace = prepare;
      Error.captureStackTrace(e, f || stack.caller);
      e = e.stack;
      Error.prepareStackTrace = oldPrepare;
      return e;
    }

    function lastReceiver(){
      return stack(lastReceiver)[2].receiver;
    }

    var CallSite = stack()[0].constructor;
    var callsiteMethods = {};

    Object.getOwnPropertyNames(CallSite.prototype).forEach(function(key){
      if (/^is|^get/.test(key)) {
        callsiteMethods[key.replace(/^is|^get/, '')] = CallSite.prototype[key];
      }
      callsiteMethods.location = CallSite.prototype.toString;
    });

    CallSite.prototype.resolve = function resolve(){
      for (var k in callsiteMethods)
        this[k] = callsiteMethods[k].call(this);
    }

  }();
}


来源:https://stackoverflow.com/questions/9777905/how-to-get-caller-from-strict-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!