Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

javascript - How to get caller from strict mode?

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  }();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...