JS回调函数的理解

来源:互联网 发布:漫画教程软件下载 编辑:程序博客网 时间:2024/05/26 22:57
JS Api 里这样解释:A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
我的理解就是方法名称作为参数传递到parent方法,parent方法执行完了之后再执行接收的参数(方法名称)
<script>function test(param){alert("传递的参数是:"+param)}function callback(func){if(func && (func instanceof Function)){func("i am param");}}callback(test);</script>
 
 模拟jquery中each方法回调函数
//回调方法没有参数,但是在运行的时候给了参数function callbackNoParam(func){if(func && (func instanceof Function)){func.call(this,"number");}}//回调方法有参数,运行的时候给了参数numberfunction callbackHasParam(func){if(func && (func instanceof Function)){func.call(this,"number");}}callbackHasParam(function test(num){ if(undefined === num){           alert("param is not past");       }else{           alert(num);       }});//弹出信息 numbercallbackNoParam(function test1(){alert(1);});//弹出信息 1
 
备注:call和apply的区别——call后面添加多个未知参数,apply第二个参数是数组
 foo.call(this, arg1,arg2,arg3) == foo.apply(this, arguments) == this.foo(arg1, arg2, arg3)
call, apply作用就是借用别人的方法来调用,就像调用自己的一样.
 
jquery关于each的源码
each : function (object, callback, args) {var name,i = 0,length = object.length,isObj = length === undefined || jQuery.isFunction(object);if (args) {if (isObj) {for (name in object) {if (callback.apply(object[name], args) === false) {break;}}} else {for (; i < length; ) {if (callback.apply(object[i++], args) === false) {break;}}}// A special, fast, case for the most common use of each} else {if (isObj) {for (name in object) {if (callback.call(object[name], name, object[name]) === false) {break;}}} else {for (var value = object[0];i < length && callback.call(value, i, value) !== false;value = object[++i]) {}}}return object;},
 
 备注:参数object是一个数组,也可以是查询出来的对象或则是控件
callback.call(object[name], name, object[name]) 表示遍历的当前对象有callback方法功能,并执行这个方法,参数name是数组坐标(序列号),object[name]是数组坐标的值(序列号对应的值)。
 
原创粉丝点击