Mazin
Mazin

Reputation: 143

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?

Upvotes: 5

Views: 113

Answers (1)

Pointy
Pointy

Reputation: 413737

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.

Upvotes: 6

Related Questions