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?
Asked
Active
Viewed 1,198 times
3 Answers
8
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

Matt
- 43,482
- 6
- 101
- 102
2
You want to implement function wrapping, check the following articles:

Christian C. Salvadó
- 807,428
- 183
- 922
- 838
1
You could simply assign the old function to a variable with a different name:
var old_parseInt = parseInt;
function parseInt(s) {
return old_parseInt(s) + 1;
}

sth
- 222,467
- 53
- 283
- 367