node package manager
Orgs are free. Discover, share, and reuse code in your team. Create a free org »



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];

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) {
  //omg console.log was called! 

For non-global functions, you assign back like this:

localFunction = extendFunction(localFunction, function(args, originalLocalFunction){
  //your magic here! 

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;
  //prevFunc is the original $.ajax 
  //call that and store the value to return 
  var ret = prevFunc.apply(this, args); = extendFunction(, function(args) {
    if (offlineArgs(args)) {
      //ignore, failure b/c of being offline 
    } else {
      var e = new Error(args[0]);
      e.stack = stackOnSend;
    //nothing returned, so extendFunction calls 
    //the original fail function and returns 
    //the value returned from it 
  return ret;

MIT licensed