Uttam Ughareja
Uttam Ughareja

Reputation: 1355

Extend javascript function without overriding current function body

Have one function as following

function JsFunction(){
//some logic already done by framework library...
}

Now, I want to add extra login on that JsFunction when I call it will perform its logic done before + the logic I added in it. I don't want to duplicate same logic from library and then add my own code. so, how can I achieve that with same function name JsFunction()??

Upvotes: 1

Views: 1636

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

If the work the function does is synchronous, it's really easy to wrap it (see below). If it does its work asynchronously, you may or may not still be able to wrap it, the details will vary depending on the implementation of the function.

Wrapping a function that works synchonrously:

var original = JsFunction;
JsFunction = function JsFunction() {
    // Do stuff before
    // ...
    // Call it
    var result = original.apply(this, arguments);
    // Do stuff after
    // ...
    return result; // Or something else if you prefer
};

The meat of that is

var result = original.apply(this, arguments);

...which uses Function#apply to call the original function with the same this that your replacement was called with and all arguments it was called with (arguments is a special pseudo-array in JavaScript containing the arguments used when calling a traditional function or method).

With ES2015+ features, you could replace the use of arguments with a rest parameter:

var original = JsFunction;
JsFunction = function JsFunction(...args) {
    // Do stuff before
    // ...
    // Call it
    var result = original.apply(this, args);
    // Do stuff after
    // ...
    return result; // Or something else if you prefer
};

Upvotes: 3

Quentin
Quentin

Reputation: 943615

Copy the old function, then create a new function which calls it (passing in any arguments and the right context), captures the return value, does something else, then returns the return value.

(function () { // In an IIFE to avoid creating a global variable
    let oldJsFunction = JsFunction;
    JsFunction = function JsFunction() {
        let return_value = oldJsFunction.apply(this, arguments);
        console.log("… and another thing");
        return return_value;
    }
)());

Upvotes: 2

Related Questions