This is how you extend an existing javascript function. Assuming that you want to preserve the existing function and the “added algorithm” is somewhat only needed to be executed based on a certain environment only.
1 2 3 4 5 6 7 8 9 10 11 12 | function abc(){ alert('abc is called'); } var abcOrig = abc; abc = function(){ abcOrig(); alert('abc has been extended!'); } alert('test 1'); abc(); alert('test 2'); abc(); |
2026 update — the technique has a name, and a couple of gotchas. 🐛
What this pattern is called is monkey-patching — you save a reference to the original function, then replace it with a wrapper that calls the original plus your extra logic. It’s still useful, especially when you need to extend a third-party function you can’t edit.
Gotcha 1: it won’t work in module / strict scopes if you use const. The 2011 example uses var and an unscoped function abc(), so reassigning the global abc is fine. In a modern ES module — or anywhere you’ve declared the function with const or let — you can’t reassign it. Patch a property on an object instead:
1 2 3 4 5 6 7 8 9 10 11 12 13 | const api = { fetchUser(id) { console.log('fetching', id); } }; const original = api.fetchUser; api.fetchUser = function (...args) { console.log('before'); const result = original.apply(this, args); console.log('after'); return result; }; |
Gotcha 2: the original example silently drops arguments, this, and the return value. The line abcOrig(); calls the original with no arguments, no this binding, and throws away whatever it returns. That’s fine for an alert, but breaks the moment you patch a real function. The robust version forwards everything:
1 2 | const result = original.apply(this, args); return result; |
Or as a one-liner using rest/spread: return original.call(this, …args);
Gotcha 3: you only get one shot per scope. If two pieces of code both monkey-patch the same function, the second one wraps the first — the order matters, and untangling it later is painful. For anything beyond a quick local override, prefer composition (a wrapper function with a different name) or class inheritance with super.
Use monkey-patching sparingly — it’s a sharp tool. But when you need to slip in an extra console.log on a function you don’t own, this is still the move. 💡