<!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>