访问V8 JavaScript中的行号(Chrome和Node.js) [英] Accessing line number in V8 JavaScript (Chrome & Node.js)

查看:115
本文介绍了访问V8 JavaScript中的行号(Chrome和Node.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

花时间使用C语言的JavaScript开发人员经常会错过使用某些类型的自省的能力,比如记录行号,以及当前方法被调用的方法。那么如果你使用的是V8(Chrome,Node.js),你可以使用下面的代码。

解决方案

  Object.defineProperty(global,'__stack',{
get:function(){
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_,stack) {return stack;};
var err = new Error;
Error.captureStackTrace(err,arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
返回堆栈;
}
});

Object.defineProperty(global,'__line',{
get:function(){
return __stack [1] .getLineNumber();
}
});

console.log(__ line);

以上将记录 19 p>

结合 arguments.callee.caller ,您可以更接近通过宏获得的有用日志类型。

JavaScript developers who have spent time in languages like C often miss the ability to use certain types of introspection, like logging line numbers, and what method the current method was invoked from. Well if you're using V8 (Chrome, Node.js) you can employ the following.

解决方案

Object.defineProperty(global, '__stack', {
  get: function(){
    var orig = Error.prepareStackTrace;
    Error.prepareStackTrace = function(_, stack){ return stack; };
    var err = new Error;
    Error.captureStackTrace(err, arguments.callee);
    var stack = err.stack;
    Error.prepareStackTrace = orig;
    return stack;
  }
});

Object.defineProperty(global, '__line', {
  get: function(){
    return __stack[1].getLineNumber();
  }
});

console.log(__line);

The above will log 19.

Combined with arguments.callee.caller you can get closer to the type of useful logging you get in C via macros.

这篇关于访问V8 JavaScript中的行号(Chrome和Node.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆