Created
September 14, 2012 13:29
-
-
Save pentaphobe/3721911 to your computer and use it in GitHub Desktop.
How to override the function call prototype in javascript, originally a stack overflow answer
This file contains hidden or 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
callLog = []; | |
/* set up an override for the Function call prototype | |
* @param func the new function wrapper | |
*/ | |
function registerOverride(func) { | |
oldCall = Function.prototype.call; | |
Function.prototype.call = func; | |
} | |
/* restore you to your regular programming | |
*/ | |
function removeOverride() { | |
Function.prototype.call = oldCall; | |
} | |
/* a simple example override | |
* nb: if you use this from the node.js REPL you'll get a lot of buffer spam | |
* as every keypress is processed through a function | |
* Any useful logging would ideally compact these calls | |
*/ | |
function myCall() { | |
Function.prototype.call = oldCall; | |
var entry = {this:this, name:this.name, args:{}}; | |
for (var key in arguments) { | |
if (arguments.hasOwnProperty(key)) { | |
entry.args[key] = arguments[key]; | |
} | |
} | |
callLog.push(entry); | |
this(arguments); | |
Function.prototype.call = myCall; | |
} | |
/* example usage | |
registerOverride(myCall); | |
console.log("hello, world!"); | |
removeOverride(myCall); | |
console.log(callLog); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
originally a Stack Overflow answer: http://stackoverflow.com/a/12425499/679950