views:

80

answers:

2

I'm looking to pass an anonymous function to another function, but it doesn't seem to be working as I'd like.

I've attached the code, I think it'd give you a better idea what I'd to do.

<script language="javascript" type="text/javascript">
function do_work(success) {
    success;
}

do_work(function () {
    alert("hello")
});

</script>

Thanks in advance for any help.

+10  A: 

You have to actually call the function:

function do_work(success) {
    success();
}
Marcel Korpel
Thank you! I knew it had to be something simple.
TFerrell
A: 

The variable success is an "instance" of Function, so you can also call apply(), that will allow you to redefine the scope :

function do_work(success) {
    var foo = {
       bar : "bat"          
    }
    success.apply(foo);
}

do_work(function () {
 alert(this.bar)
});
mexique1