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

前端 未结 2 1713
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 17:51

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 be

相关标签:
2条回答
  • 2020-12-20 18:25

    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 讨论(0)
  • 2020-12-20 18:33

    You have to actually call the function:

    function do_work(success) {
        success();
    }
    
    0 讨论(0)
提交回复
热议问题