Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  48] [ 5]  / answers: 1 / hits: 31111  / 12 Years ago, sun, july 8, 2012, 12:00:00

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.


More From » node.js

 Answers
36
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.


[#84393] Friday, July 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
walker

Total Points: 726
Total Questions: 91
Total Answers: 106

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;