JavaScript alias method chain?

In JavaScript, how could you create a new function with the same name as an existing function, and also save the original function so that it can be called from a new one?

+3
source share
3 answers

You can pass the original function to an anonymous function that returns a replacement function that has access to the original function.

eg.

parseInt = (function parseInt(original) {
    return function (x) {
        console.log("original would've returned " + original(x));

        // just random 'new' functionality
        return (x | 0) * 2;
    };
}(parseInt));

Output Example:

>> parseInt(10);
<< original would've returned 10
<< 20
+8
source

If you want to implement feature packaging, check out the following articles:

+3
source

You can simply assign the old function to a variable with a different name:

var old_parseInt = parseInt;

function parseInt(s) {
   return old_parseInt(s) + 1;
}
+1
source

Source: https://habr.com/ru/post/1749322/


All Articles