Let’s say we have a class with an existing method.
var MyClass = function() { };
MyClass.prototype = { myMethod: function(parameter1) { console.log(‘called from original method ‘ + parameter1); }}
We can create an instance of the class and call it’s method like this:
var obj = new MyClass();
obj.myMethod(‘p’);
>called from original method p
Now, suppose that for this instance obj, we want to modify the definition of myMethod in such a way that some additional code is executed. But at the same time, we don’t want to lose the original code. In the end, we want that code to be executed as well.
We can achieve this by first storing the original method definition in a variable before modifying the method. Then in the modified method, we can call the original code as well by referring to this variable.
var origFunction = obj.myMethod;
obj.myMethod = function() { console.log(‘called from the modified function’); if(origFunction){origFunction.apply(this, arguments); }}
Now, when we execute myMethod, we get the following output:
obj.myMethod(‘p’);
> called from the modified function
> called from original method p
Note: This was about modifying the object instance. Not the original class. The original class is still intact as you can verify below:
var obj1 = new MyClass();
obj1.myMethod(‘p’);
> called from original method p