Forked from pentaphobe/function.prototype.override.js
Created
March 15, 2017 07:59
-
-
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
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
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