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.
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.
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.
Function in the other object.
The Proxy pattern might help you:
You could do something like this:
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) ina
, not store the outer function itself ina
.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.
Usage for example with Bootstrap:
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.
The examples above don't correctly apply
this
or passarguments
correctly to the function override. Underscore _.wrap() wraps existing functions, appliesthis
and passesarguments
correctly. See: http://underscorejs.org/#wrap