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?
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 .
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.
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.
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.
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