js回调函数的简单理解

什么是回调? 

  A callback is a function that is passed as an argument to another function and is executed 
after its parent function has completed。
  字面上的理解,回调函数就是传递一个参数化的函数,就是将这个函数作为一个参数传到另一个主函数里面,
当那一个主函数执行完之后,再执行传进去的作为参数的函数。走这个过程的参数化的函数 就叫做回调函数。
换个说法也就是被作为参数传递到另一个函数(主函数)的那个函数就叫做 回调函数

例子:

1.基本方法

<script >
    function doSomething(callback) {
    //
    // Call the callback
        callback('stuff', 'goes', 'here');
    } 
    function foo(a, b, c) {
    // I'm the callback
    alert(a + " " + b + " " + c);
    } 
    doSomething(foo); 
</script>

或者用匿名函数的形式:

<script>
    function dosomething(damsg, callback){
        alert(damsg);
        if(typeof callback == "function") 
        callback();
    } 
    dosomething("回调函数", function(){
        alert("和 jQuery 的 callbacks 形式一样!");
    }); 
</script>            

.call调用:

 <script>
 2 
 3     function Thing(name) {
 4         this.name = name;
 5     }
 6     Thing.prototype.doSomething = function(handle) {
 7         // alert(this.name);
 8         //将值传回给handle函数
 9         handle.call(this,this.name);
10         // handle(this.name); --> undefind
11     }
12     // function foo() {
13     // alert(this.name);
14     // }
15     var t = new Thing('Joe');
16     t.doSomething(function(a){
17     alert(a);
18     }); // Alerts "Joe" via `foo`    
</script>

猜你喜欢

转载自www.cnblogs.com/szxEPoch/p/11728303.html
今日推荐