[前端JS學習筆記]JavaScript CallBack

1、概念介紹

  CallBack : "回調" 。 在spring優秀框架回調無處不在, 回調的運用場景不少, 如 swt事件監聽、netty等。它的主要做用是提升程序執行效率, 一段代碼執行時沒必要等另外一段代碼執行結束才繼續往下run。 在JavaScript也不例外。 javascript

2、js 回調語法

傳遞函數做爲回調html

function(ag1,ag2...,callback) {java

  // 業務邏輯代碼spring

框架

js 代碼study.js函數

window.mytest = function(str, callback) {
    printStr(str) ;
    var res = test_callback();
    callback(res);
}

function printStr(str) {
    alert(str);
}

function test_callback() {
    return "回調測試";
}

 html代碼 studyJS.html測試

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />

</head>
<body>

    <button onclick="test_callback()">test</button>

</body>

<script src="js/study/study.js" type="text/javascript"></script>

<script>
    
    
    mytest("加油", function(data) {
        console.log(data);
    })

</script>

</html>

分析 : 打開 studyJS.html, 會執行mytest()方法。執行以後,回去回調業務定義的回調函數, 如上圖spa

function(data) {
   console.log(data);
}

因此控制檯會輸出 」加油「!!!netty

相關文章
相關標籤/搜索