How to pass and call a function as an argument in Javascript?

I want to pass an anonymous function to another function, but it doesn't seem to work as I would like.

I have attached the code, I think this will give you a better idea of ​​what I should do.

How to successfully pass a function as an argument and then call it?

<script language="javascript" type="text/javascript"> function do_work(success) { success; } do_work(function () { alert("hello") }); </script> 
+7
javascript function
source share
2 answers

You should actually call the function:

 function do_work(success) { success(); } 
+14
source share

The success of a variable is an β€œinstance” of Function , so you can also call apply (), which allows you to override the scope:

 function do_work(success) { var foo = { bar : "bat" } success.apply(foo); } do_work(function () { alert(this.bar) }); 
0
source share

All Articles