Get stack trace in JavaScript (v8 only)

道理就是应用Error, 以及v8特有的API: JavaScript stack trace API.
运用这类要领能够获取到相当多的信息,
比方函数地点的文件的文件名, 行号列号等等…
不过瑕玷是只要v8支撑.
其他浏览器能够应用arguments.caller来追溯挪用栈.

直接上代码:

// hook the prepare function
Error.prepareStackTrace=function(err,stack){
  // err: the Error object.
  // stack: stack info, an array of `CallSite`.
  // return full info of the stack.
  return stack;
};

// trace function
function trace(){
  var obj={};
  Error.captureStackTrace(obj);
  // or just use: var obj=new Error();
  var stack=obj.stack;
  // remove this function from stack
  stack=stack.slice(1);
  return stack;
}

运用:

(function callee(){
  console.assert(trace()[0].getFunction()===callee);
})();
    原文作者:IntPtr
    原文地址: https://segmentfault.com/a/1190000000742286
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞