使用过 C 等语言的 JavaScript 开发人员经常错过使用某些类型的内省(introspection)的能力,例如记录行号,以及当前方法是从哪个方法调用的。好吧,如果您使用的是 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;
return stack;
}
});
Object.defineProperty(global, '__line', {
get: function(){
return __stack[1].getLineNumber();
}
});
console.log(__line);
上面会记录19
。
结合 arguments.callee.caller
你可以更接近你在 C 中通过宏获得的有用的日志类型。
关于javascript - 在 V8 JavaScript (Chrome & Node.js) 中访问行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11386492/