I have a function I can't modify:
function addToMe() { doStuff(); }
Can I add to this function? Obviously this syntax is terribly wrong but it's the general idea...
function addToMe() { addToMe() + doOtherStuff(); }
add() The add() method inserts a new element with a specified value in to a Set object, if there isn't an element with the same value already in the Set .
The JavaScript Set add() method is used to add an element to Set object with a specified value. Each element must have a unique value.
const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.
You could store a reference to the original function, and then override it, with a function that calls back the original one, and adds the functionality you desire:
var originalFn = addToMe; addToMe = function () { originalFn(); // call the original function // other stuff };
You can do this because JavaScript functions are first-class objects.
Edit: If your function receives arguments, you should use apply to pass them to the original function:
addToMe = function () { originalFn.apply(this, arguments); // preserve the arguments // other stuff };
You could also use an auto-executing function expression with an argument to store the reference of the original function, I think it is a little bit cleaner:
addToMe = (function (originalFn) { return function () { originalFn.apply(originalFn, arguments); // call the original function // other stuff }; })(addToMe); // pass the reference of the original function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With