本文介绍了如何从严格模式获得呼叫者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以混合严格和非严格的代码。但即使对它的调用不是严格的代码,你也不能使用调用者。有没有人知道任何解决方法?

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?

我试过这个:

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


推荐答案

这是一个只在V8中有效的邪恶黑客。 140字节版本:

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}

而不那么神秘的版本

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

  }();
}

这篇关于如何从严格模式获得呼叫者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-12 23:07