Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias method chain in JavaScript?

In JavaScript, how could you create a new function with the same name as an existing function, while also preserving the original function so it could be called from within the new one?


1 Answers

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

E.g.

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

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

Example output:

>> parseInt(10);
<< original would've returned 10
<< 20
like image 153
Matt Avatar answered Apr 14 '26 23:04

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!