Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to a javascript function

Tags:

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(); } 
like image 929
Peter Craig Avatar asked Nov 02 '09 02:11

Peter Craig


People also ask

Is there an add function in JavaScript?

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 .

What is ADD () in JavaScript?

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.

How do you add two numbers in JavaScript using functions?

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.


1 Answers

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 
like image 141
Christian C. Salvadó Avatar answered Jan 18 '23 23:01

Christian C. Salvadó