Created
September 5, 2016 22:29
-
-
Save balbuf/e09343c13c71f0023f1f015be32231b3 to your computer and use it in GitHub Desktop.
Monitor a type of object by wrapping all of its prototype methods in a function that logs messages in the console when fired.
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
/** | |
* Provides a rudimentary means of debugging by snooping on method calls to a particular kind of object. | |
* All of the object's prototypal methods will be wrapped in a new function that provides information | |
* in the console. When the method is called, the object type, method, and params will be logged in | |
* the console, then the original method will be called with the proper arguments. | |
* | |
* @param {function} obj object constructor to snoop (not an instantiated object) | |
* @return {function} the same object for chaining | |
*/ | |
function prototypeSnooper(obj) { | |
for (var method in obj.prototype) { | |
// try/catch is necessary because some protoype props are untouchable | |
// (like they literally throw an error just by referencing them) | |
try { | |
if (typeof obj.prototype[method] !== 'function') continue; | |
obj.prototype[method] = (function(func, method) { | |
return function() { | |
console.log(obj.name + '::' + method + '(' + Array.prototype.join.call(arguments, ', ') + ')'); | |
return func.apply(this, arguments); | |
}; | |
})(obj.prototype[method], method); | |
} catch(e) {}; | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment