码迷,mamicode.com
首页 > Web开发 > 详细

js回调函数的简单理解

时间:2019-10-23 19:46:18      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:执行   简单   --   fun   back   pass   code   函数   font   

什么是回调? 

  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>

 

js回调函数的简单理解

标签:执行   简单   --   fun   back   pass   code   函数   font   

原文地址:https://www.cnblogs.com/szxEPoch/p/11728303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!