extendFunction.js
The easiest way to overwrite other functions with additional functionality
Example:
Let's modify alert to keep a history array of the logs:
window.alertHistory = [];
extendFunction('alert', function(args) {
var message = args[0];
alertHistory.push(message);
});
Test it:
alert('a message');
if (alertHistory[0] === 'a message') {
alert('oh geez this function is powerful!');
}
Now let's add ' from DevinRhode2' to every alert message
extendFunction('alert', function(args, nativeAlert) {
nativeAlert(message + ' from DevinRhode2')
});
Works for methods too:
extendFunction('console.log', function(args, nativeConsoleLog) {
});
For non-global functions, you assign back like this:
localFunction = extendFunction(localFunction, function(args, originalLocalFunction){
});
Modify return values:
extendFunction('strangeModule.strangeMethod', function(args, prevFunc) {
var returnValue = prevFunc.apply(this, args);
returnValue.extraInfo = 'idk';
return returnValue;
});
Or promises:
extendFunction('$.ajax', function(args, prevFunc) {
var stackOnSend = new Error().stack;
var ret = prevFunc.apply(this, args);
ret.fail = extendFunction(ret.fail, function(args) {
if (offlineArgs(args)) {
} else {
var e = new Error(args[0]);
e.stack = stackOnSend;
onuncaughtException(e);
}
});
return ret;
});
MIT licensed