show the function call chain [ 782 views ]
Goal: catch the call chains in javascript
I want to see my program’s footprint.
So the hard way is to build a log mechanism… The easier is to use my _trace utility.
_chain function.
To achieve my goal I need to watch all my functions. This is not a complicated task if I use the _trace for all functions of my object like this:
(function() { // _chain /* usage 1. I have only a simple way to do this this._chain(); */ TypeExtend(Object, '_chain', function() { for(var i in this){ if(typeof this[i] === "function") { this._trace(i, true); } } console.obj('_chain applied to', this); }); }());
The result is in the console window. I can follow the call chain. I can see the called functions with the arguments.
I’ve extended the object class again and modified the _trace method
(function() { // _trace, _watch, _catch capability /* usage 1. simple trace and watch this._trace('myFunctionName'); ... or ... _trace.call(this, 'myFunctionName'); this._watch('myVariableName'); ... or ... _watch.call(this, 'myVariableName'); 2. function bind on variable set this._catch('myVariableName', function(){...}); ... or ... _catch.call(this, 'myVariableName', function(){...}); */ var _trace_level = 1; TypeExtend(Object, '_trace', function(funcName, useChain) { if(typeof(this[funcName]) != 'function'){_watch.call(this, funcName); return false;} if(this['__' + funcName]){return false;} this['__' + funcName] = this[funcName]; this[funcName] = function(){ var a = arguments, _tl = _trace_level; arguments.callee.caller.toString() && _trace_level++; var aa = '', aar = []; for(var ar in a){ a[ar] && aar.push(a[ar].toString()); } aa = aar.join(','); if(useChain){ if(_tl < _trace_level){ console.group(funcName + ' (' + aa + ')'); } else{ console.log(funcName + ' (' + aa + ')'); } } else{ console.traceEx('_trace: ' + ' '.repeat(_trace_level) + funcName, 'background: rgba(207, 181, 42, 0.6); color: #000;', arguments); } var ret = this['__' + funcName](a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[8],a[10]); if(_tl < _trace_level){ console.groupEnd(); } _trace_level = _tl; return ret; }; !useChain && console.info('_trace applied to ' + funcName); return true; }); _trace = function(fn){ this._trace(fn); }; [/js] To show the call chain just put this to the start point of your code. <strong>this</strong> is my class to investigate. [js] this._chain();
see also: extender – Object