Overriding a JavaScript function while referencing the original

JavascriptOverridingUser Defined-Functions

Javascript Problem Overview


I have a function, a(), that I want to override, but also have the original a() be performed in an order depending on the context. For example, sometimes when I'm generating a page I'll want to override like this:

function a() {
    new_code();
    original_a();
}

and sometimes like this:

function a() {
    original_a();
    other_new_code();
}

How do I get that original_a() from within the over-riding a()? Is it even possible?

Please don't suggest alternatives to over-riding in this way, I know of many. I'm asking about this way specifically.

Javascript Solutions


Solution 1 - Javascript

You could do something like this:

var a = (function() {
    var original_a = a;

    if (condition) {
        return function() {
            new_code();
            original_a();
        }
    } else {
        return function() {
            original_a();
            other_new_code();
        }
    }
})();

Declaring original_a inside an anonymous function keeps it from cluttering the global namespace, but it's available in the inner functions.

Like Nerdmaster mentioned in the comments, be sure to include the () at the end. You want to call the outer function and store the result (one of the two inner functions) in a, not store the outer function itself in a.

Solution 2 - Javascript

The Proxy pattern might help you:

(function() {
    // log all calls to setArray
    var proxied = jQuery.fn.setArray;
    jQuery.fn.setArray = function() {
        console.log( this, arguments );
        return proxied.apply( this, arguments );
    };
})();

> The above wraps its code in a function to hide the "proxied"-variable. It saves jQuery's setArray-method in a closure and overwrites it. The proxy then logs all calls to the method and delegates the call to the original. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method.

Solution 3 - Javascript

Thanks guys the proxy pattern really helped.....Actually I wanted to call a global function foo.. In certain pages i need do to some checks. So I did the following.

//Saving the original func
var org_foo = window.foo;

//Assigning proxy fucnc
window.foo = function(args){
    //Performing checks
    if(checkCondition(args)){
        //Calling original funcs
        org_foo(args);
    }
};

Thnx this really helped me out

Solution 4 - Javascript

You can override a function using a construct like:

function override(f, g) {
    return function() {
        return g(f);
    };
}

For example:

 a = override(a, function(original_a) {
      if (condition) { new_code(); original_a(); }
      else { original_a(); other_new_code(); }
 });

Edit: Fixed a typo.

Solution 5 - Javascript

Passing arbitrary arguments:

a = override(a, function(original_a) {
    if (condition) { new_code(); original_a.apply(this, arguments) ; }
    else { original_a.apply(this, arguments); other_new_code(); }
});

Solution 6 - Javascript

The answer that @Matthew Crumley provides is making use of the immediately invoked function expressions, to close the older 'a' function into the execution context of the returned function. I think this was the best answer, but personally, I would prefer passing the function 'a' as an argument to IIFE. I think it is more understandable.

   var a = (function(original_a) {
        if (condition) {
            return function() {
                new_code();
                original_a();
            }
        } else {
            return function() {
                original_a();
                other_new_code();
            }
        }
    })(a);

Solution 7 - Javascript

The examples above don't correctly apply this or pass arguments correctly to the function override. Underscore _.wrap() wraps existing functions, applies this and passes arguments correctly. See: http://underscorejs.org/#wrap

Solution 8 - Javascript

I had some code written by someone else and wanted to add a line to a function which i could not find in the code. So as a workaround I wanted to override it.

None of the solutions worked for me though.

Here is what worked in my case:

if (typeof originalFunction === "undefined") {
	originalFunction = targetFunction;
    targetFunction = function(x, y) {
		//Your code
        originalFunction(a, b);
        //Your Code
	};	
}

Solution 9 - Javascript

I've created a small helper for a similar scenario because I often needed to override functions from several libraries. This helper accepts a "namespace" (the function container), the function name, and the overriding function. It will replace the original function in the referred namespace with the new one.

The new function accepts the original function as the first argument, and the original functions arguments as the rest. It will preserve the context everytime. It supports void and non-void functions as well.

function overrideFunction(namespace, baseFuncName, func) {
    var originalFn = namespace[baseFuncName];
    namespace[baseFuncName] = function () {
        return func.apply(this, [originalFn.bind(this)].concat(Array.prototype.slice.call(arguments, 0)));
    };
}

Usage for example with Bootstrap:

overrideFunction($.fn.popover.Constructor.prototype, 'leave', function(baseFn, obj) {
    // ... do stuff before base call
    baseFn(obj);
    // ... do stuff after base call
});

I didn't create any performance tests though. It can possibly add some unwanted overhead which can or cannot be a big deal, depending on scenarios.

Solution 10 - Javascript

In my opinion the top answers are not readable/maintainable, and the other answers do not properly bind context. Here's a readable solution using ES6 syntax to solve both these problems.

const orginial = someObject.foo;
someObject.foo = function() {
  if (condition) orginial.bind(this)(...arguments);
};

Solution 11 - Javascript

So my answer ended up being a solution that allows me to use the _this variable pointing to the original object. I create a new instance of a "Square" however I hated the way the "Square" generated it's size. I thought it should follow my specific needs. However in order to do so I needed the square to have an updated "GetSize" function with the internals of that function calling other functions already existing in the square such as this.height, this.GetVolume(). But in order to do so I needed to do this without any crazy hacks. So here is my solution.

Some other Object initializer or helper function.

this.viewer = new Autodesk.Viewing.Private.GuiViewer3D(
  this.viewerContainer)
var viewer = this.viewer;
viewer.updateToolbarButtons =  this.updateToolbarButtons(viewer);

Function in the other object.

updateToolbarButtons = function(viewer) {
  var _viewer = viewer;
  return function(width, height){ 
blah blah black sheep I can refer to this.anything();
}
};

Solution 12 - Javascript

Not sure if it'll work in all circumstances, but in our case, we were trying to override the describe function in Jest so that we can parse the name and skip the whole describe block if it met some criteria.

Here's what worked for us:

function describe( name, callback ) {
  if ( name.includes( "skip" ) )
    return this.describe.skip( name, callback );
  else
    return this.describe( name, callback );
}

Two things that are critical here:

  1. We don't use an arrow function () =>.

    Arrow functions change the reference to this and we need that to be the file's this.

  2. The use of this.describe and this.describe.skip instead of just describe and describe.skip.

Again, not sure it's of value to anybody but we originally tried to get away with Matthew Crumley's excellent answer but needed to make our method a function and accept params in order to parse them in the conditional.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevView Question on Stackoverflow
Solution 1 - JavascriptMatthew CrumleyView Answer on Stackoverflow
Solution 2 - JavascriptPhilHoyView Answer on Stackoverflow
Solution 3 - JavascriptNaresh SView Answer on Stackoverflow
Solution 4 - JavascriptHai PhanView Answer on Stackoverflow
Solution 5 - JavascriptEdric GarranView Answer on Stackoverflow
Solution 6 - JavascriptRodrigo HernandezView Answer on Stackoverflow
Solution 7 - JavascriptnevfView Answer on Stackoverflow
Solution 8 - JavascriptSagar SodahView Answer on Stackoverflow
Solution 9 - JavascriptZoltán TamásiView Answer on Stackoverflow
Solution 10 - JavascriptJames L.View Answer on Stackoverflow
Solution 11 - JavascriptSteckDEVView Answer on Stackoverflow
Solution 12 - JavascriptJoshua PinterView Answer on Stackoverflow