Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass a function as a parameter and then execute it in a jquery function

I was wondering which is the way to make this simple (and maybe stupid) thing with jQuery.

I have a function like this:

function setSomething() { 
    make some stuff; 
}

and then another function like this:

generalFunction(par1, par2, par3) { 
    do other stuff; 
    execute function called in par3;    
}

Well, if I write something like this it doesn't work:

c=setSomething(); 
generalFunction(a, b, c);

So what's the way to call a function as a parameter of another function and then execute it inside?

I hope I was clear enough.

Any help will be appreciated.

Thank you in advance for your attention.

like image 370
bobighorus Avatar asked Apr 02 '12 10:04

bobighorus


People also ask

How can you pass parameters to jQuery function?

If you want to pass more than one parameter to the URL,use data as data:{id:'123' , name:"MyName"} where the 123 is the value of the parameter id myName is the value for the parameter name the value here can be string or variable having the value to be passed.

How do you pass a function as a parameter?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.

Can you use a function as a parameter of another function?

Functions can be passed into other functionsFunctions, like any other object, can be passed as an argument to another function.

Can we pass function as a parameter in JavaScript?

Functions in the functional programming paradigm can be passed to other functions as parameters. These functions are called callbacks. Callback functions can be passed as arguments by directly passing the function's name and not involving them.


1 Answers

leave out the parentheses , you can then call the parameter as a function inside your "generalFunction" function.

setSomething(){
   // do other stuff  
}

generalFunction(par1, par2, par3) { 
    // do stuff...

    // you can call the argument as if it where a function ( because it is !)
    par3();
}

generalFunction(a, b, setSomething);
like image 188
Willem D'Haeseleer Avatar answered Nov 02 '22 23:11

Willem D'Haeseleer