Last active
August 29, 2015 14:09
-
-
Save kennethlynne/2d0da78ef15029e434cb to your computer and use it in GitHub Desktop.
DIY javascript stack trace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copied from http://helephant.com/2007/05/12/diy-javascript-stack-trace/ - read more about the approach there | |
Function.prototype.trace = function() | |
{ | |
var trace = []; | |
var current = this; | |
while(current) | |
{ | |
trace.push(current.signature()); | |
current = current.caller; | |
} | |
return trace; | |
} | |
Function.prototype.signature = function() | |
{ | |
var signature = { | |
name: this.getName(), | |
params: [], | |
toString: function() | |
{ | |
var params = this.params.length > 0 ? | |
"'" + this.params.join("', '") + "'" : ""; | |
return this.name + "(" + params + ")" | |
} | |
}; | |
if(this.arguments) | |
{ | |
for(var x=0; x<this .arguments.length; x++) | |
signature.params.push(this.arguments[x]); | |
} | |
return signature; | |
} | |
Function.prototype.getName = function() | |
{ | |
if(this.name) | |
return this.name; | |
var definition = this.toString().split("\n")[0]; | |
var exp = /^function ([^\s(]+).+/|>; | |
if(exp.test(definition)) | |
return definition.split("\n")[0].replace(exp, "$1") || "anonymous"; | |
return "anonymous"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment