21

I have a function I can't modify:

function addToMe() { doStuff(); }

Can I add to this function? Obviously this syntax is terribly wrong but it's the general idea...

function addToMe() { addToMe() + doOtherStuff(); }

1 Answer 1

42

You could store a reference to the original function, and then override it, with a function that calls back the original one, and adds the functionality you desire:

var originalFn = addToMe;

addToMe = function () {
  originalFn(); // call the original function
  // other stuff
};

You can do this because JavaScript functions are first-class objects.

Edit: If your function receives arguments, you should use apply to pass them to the original function:

addToMe = function () {
  originalFn.apply(this, arguments); // preserve the arguments
  // other stuff
};

You could also use an auto-executing function expression with an argument to store the reference of the original function, I think it is a little bit cleaner:

addToMe = (function (originalFn) {
  return function () {
    originalFn.apply(originalFn, arguments); // call the original function
    // other stuff
  };
})(addToMe); // pass the reference of the original function
Sign up to request clarification or add additional context in comments.

2 Comments

yep that's probably the simplest solution!
You should add a second return-statement before originalFn!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.