Skip to content Skip to sidebar Skip to footer

JS: Call A Function After Another Without Touching The Original Function?

I am trying to extend a third party library on a specific page, but I don't want to change any of the third party code. I know the name of the functions the third party library cal

Solution 1:

If there is a way for you to get a reference to the function you want to extend you can "monkey-patch" it like this:

var fnOriginalFunction = functionYouWantToExtend;
functionYouWantToExtend = function() {
    fnOriginalFunction.apply(this, arguments);

    // your code here
};

This effectively re-writes the function you want to extend in a somewhat-seamless manner.

More information about monkey-patching.


Solution 2:

"I am trying to extend a third party library on a specific page, but I don't want to change any of the third party code"

This can't be done. You have to alter the code somehow to react to it unless the code provides an event emitting mechanism or something alike.

The way to approach this without affecting the library is to overwrite the function you want to extend by having it do everything it already did and add your custom behavior on top.

For example:

const Library = {
  method() {
    console.log('I am the library method');
  }
}

const unalteredMethod = Library.method;
Library.method = function() {
  unalteredMethod.apply(this, arguments);
  console.log('my custom behavior');
}

Library.method();

Post a Comment for "JS: Call A Function After Another Without Touching The Original Function?"