Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i pass variable in parameter as a function?

if i have this function:

   function test(x){  
   alert(x);
   }

when I run it as:

test('hello world');

i will get a window.

good, instead of passing a parameter as string.. i need pass a parameter as function, like that:

   function test(x){  
   x;
   }

then i run:

   test(alert('hello world'));

So how can I pass a function as a parameter to another function?

like image 344
Mazin Avatar asked Dec 31 '15 20:12

Mazin


People also ask

How do you pass a parameter to a variable?

If you want the called method to change the value of the argument, you must pass it by reference, using the ref or out keyword. You may also use the in keyword to pass a value parameter by reference to avoid the copy while guaranteeing that the value will not be changed. For simplicity, the following examples use ref .

Can a function use variables as parameters?

A function can take parameters which are just values you supply to the function so that the function can do something utilising those values. These parameters are just like variables except that the values of these variables are defined when we call the function and are not assigned values within the function itself.

Can we pass a function as a parameter in for function?

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.


1 Answers

You have to have x actually be a function, and you have to actually call it:

function test(x) {
  x();
}

test(function() { alert("Hello World!"); });

By itself, alert("Hello World!") is just an expression, not a function. The only way to syntactically turn an expression into a function (without immediately evaluating it, at least) is with that function instantiation syntax above.

like image 138
Pointy Avatar answered Oct 13 '22 12:10

Pointy