Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tomcask/6fe539d630790aa78eabb5caddd06e6e to your computer and use it in GitHub Desktop.
Save tomcask/6fe539d630790aa78eabb5caddd06e6e to your computer and use it in GitHub Desktop.
How to override the function call prototype in javascript, originally a stack overflow answer
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