Custom method implementation pattern in Javascript

Viewed 156

I found this kind of syntax in Javascript :

myVariable = myClass.prototype.simpleMethod;
myClass.prototype.simpleMethod = function(params)
{
    myVariable.apply(this, arguments);
    ....
};

What's the purpose of this pattern? Does the new function combine old and new implementation? Or replace it within '....'? Can you provide a detailed explanation of this?

EDIT: Problem solved. I marked the Nas answer as accepted but the spender one could be relevant as well.

2 Answers

It's the equivalent of an override that calls the original, base implementation. The original implementation is stored in a variable. Now the original implementation is overwritten with a new function. The first thing the new function does (with the call to myVariable.apply(this, arguments)) is call the original implementation with the same arguments, ensuring that this is preserved. See Function.prototype.apply for more details.

arguments is a variable that is provided by the JavaScript run-time in the context of any called function. It is an array that contains the arguments which were passed to the currently executing function (i.e. the most immediate function in the callstack). See here for details.

This is a way to wrap and "extend" the simpleMethod.

It could be useful if you want to define a behaviour before and/or after a method is run.

Here is line by line explanation on what each statement from your example does.

// We save a reference to the current implementation of the "simpleMethod"
myVariable = myClass.prototype.simpleMethod;

// We change the "simpleMethod" implementation to have a "new implementation"
myClass.prototype.simpleMethod = function(params)
{
    // as myVariable store "the old" implementation we call the old impl. 
    // having the same this as the wrapping function.
    // passing the same args, passed to the "wrapper function"
    myVariable.apply(this, arguments);
    ....
};

The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0. (from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)

Related