开发者

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

开发者 https://www.devze.com 2022-12-31 21:02 出处:网络
I\'m looking to pass an anonymous functio开发者_如何学JAVAn to another function, but it doesn\'t seem to be working as I\'d like.

I'm looking to pass an anonymous functio开发者_如何学JAVAn 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.

How do I successfully pass a function as an argument, and then invoke it?

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

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

</script>


You have to actually call the function:

function do_work(success) {
    success();
}


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)
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号