<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>回调函数callback的使用方法</title> </head> <body> <button >点击</button> <script type="text/javascript"> var name = 'shimily'; var age = 20; function goTime(callback) { console.log('hello'); callback && callback(); //有回调就执行,没有回调就不执行 console.log(age,'========='); } function actEnd(){ console.log(name); } /*调用方法*/ goTime(); //如果不传方法,则代表不需要执行回调 goTime(actEnd); //test是个方法,此处可以打印出test的值 </script> </body> </html>
打印结果如下:
======================================================================
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h2>callback方法</h2> <script type="text/javascript"> /*活动结束的方法*/ function actEnd() { console.log("活动已经结束"); } /*活动方法*/ function goTime(ele,callback){ console.log(ele); callback && callback(); } goTime('#timer',actEnd); </script> <!-- ====================间隔======================= --> <script type="text/javascript"> /*闭包方法*/ function callback(callback) { console.log(1111); if (callback != null) { callback(); } } /*游戏方法*/ function game(ele){ callback(function () { console.log(ele); }); } game('#game'); </script> </body> </html>