<html>
<head>
<title>JavaScript Stack Trace</title>
<script type="text/javascript">
// Stack trace logic
Function.prototype.trace = function () {
var trace = []
, 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 = '';
if (this.params.length > 0) {
params = '"' + this.params.join('", "') + '"';
}
return this.name + '(' + params + ')';
}
};
if (this.arguments) {
for (var i = 0, len = this.arguments.length; i < len; i++) {
signature.params.push(this.arguments[i]);
}
}
return signature;
};
Function.prototype.getName = function () {
if (this.name) {
return this.name;
}
var definition = this.toString().split('\n')[0]
, exp = /^function ([^\s(]+).+/;
if (exp.test(definition)) {
return definition.split('\n')[0].replace(exp, '$1') || 'anonymous';
}
return 'anonymous';
};
// Test
function a (say) {
var trace = arguments.callee.trace();
document.getElementById('output').innerHTML = trace.join('<br/>\n');
}
function b () {
a('hello world');
}
</script>
</head>
<body>
<input type="button" value="stack trace" onclick="b()">
<div id="output"></div>
</body>
</html>
Комментариев нет:
Отправить комментарий