Skip to content

Instantly share code, notes, and snippets.

@rfletcher
Created January 7, 2010 19:58
Show Gist options
  • Save rfletcher/271509 to your computer and use it in GitHub Desktop.
Save rfletcher/271509 to your computer and use it in GitHub Desktop.
// add a log() method to all function objects
Function.prototype.log = function() {
var __method = this;
return function() {
var name = /function\s*(.*)\s*\(/.exec( __method );
console.log( "called " + ( name[1] || "[unknown]" ) + "()", arguments );
return __method.apply( null, arguments );
}
}
// declare some function as normal
function foo() {
console.log( "I'm foo!" );
return true;
}
// call the function, no logging by default. output:
// I'm foo!
foo( { x: 'yz' } );
// turn logging on
foo = foo.log();
// calls are now logged to the console. output:
// called foo() [Object x=yz]
// I'm foo!
foo( { x: 'yz' } );
// alternatively, you could have turned it on when it was declared
/*
var foo = (function foo() {
console.log( "I'm foo!" );
return true;
}).log();
*/
// works for anonymous functions too, but output is a little different. output:
// called [unknown]() [Object x=yz]
// I'm anonymous
(function() {
console.log( "I'm anonymous" );
}).log()( { x: 'yz' } );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment