js中回呼函數的學習筆記,回呼函數學習筆記

來源:互聯網
上載者:User

js中回呼函數的學習筆記,回呼函數學習筆記

回呼函數是什麼在學習之前還真不知道js回呼函數怎麼使用及作用了,下面本文章把我在學習回呼函數例子給各位同學介紹一下吧,有需瞭解的同學不防進入參考。

回呼函數原理:

我現在出發,到了通知你”
這是一個非同步流程,“我出發”這個過程中(函數執行),“你”可以去做任何事,“到了”(函數執行完畢)“通知你”(回調)進行之後的流程

例子

1.基本方法

<script language="javascript" type="text/javascript">function doSomething(callback) {// … // Call the callbackcallback('stuff', 'goes', 'here');} function foo(a, b, c) {// I'm the callbackalert(a + " " + b + " " + c);} doSomething(foo); </script>

或者用匿名函數的形式

<script language="javascript" type="text/javascript"> function dosomething(damsg, callback){  alert(damsg);  if(typeof callback == "function")   callback(); } dosomething("回呼函數", function(){  alert("和 jQuery 的 callbacks 形式一樣!"); }); </script>

 
2.進階方法
 
使用javascript的call方法

<script language="javascript" type="text/javascript">function Thing(name) {this.name = name;}Thing.prototype.doSomething = function(callback) {// Call our callback, but using our own instance as the contextcallback.call(this);} function foo() {alert(this.name);} var t = new Thing('Joe');t.doSomething(foo); // Alerts "Joe" via `foo`</script>

 
傳參數

<script language="javascript" type="text/javascript"> function Thing(name) {this.name = name;}Thing.prototype.doSomething = function(callback, salutation) {// Call our callback, but using our own instance as the contextcallback.call(this, salutation);} function foo(salutation) {alert(salutation + " " + this.name);} var t = new Thing('Joe');t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo`</script>

使用 javascript 的 apply 傳參數

<script language="javascript" type="text/javascript">function Thing(name) {this.name = name;}Thing.prototype.doSomething = function(callback) {// Call our callback, but using our own instance as the contextcallback.apply(this, ['Hi', 3, 2, 1]);} function foo(salutation, three, two, one) {alert(salutation + " " + this.name + " – " + three + " " + two + " " + one);} var t = new Thing('Joe');t.doSomething(foo); // Alerts "Hi Joe – 3 2 1" via `foo`</script>

例子
//假如提供的資料來源是一整數,為某學生的分數,當num<=0,由底層處理,當n>0時由高層處理.

//將下面這個函數拷貝下來存檔為1.js

function f(num,callback){ if(num<0) {  alert("調用低層函數處理!"); alert("分數不能為負,輸入錯誤!");  }else if(num==0){  alert("調用低層函數處理!"); alert("該學生可能未參加考試!"); }else{ alert("調用高層函數處理!"); callback(); }}

//將下面這個test.html檔案存檔與1.js在一個目錄下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><script src="1.js" type="text/javascript"></script><title>無標題文檔</title><script type="text/javascript"> function test(){  var p=document.getElementById("pp"); pp.innerText="";  var num=document.getElementById("score").value; f(num,function(){ //匿名高層處理函數 if(num<60) alert("未及格!"); else if(num<=90) alert("該產生績優良!"); else alert("該產生績優秀!"); }) pp.innerText="by since1978 qq558064!" }</script></head><body><p>回呼函數樣本:當學產生績score<=0分時候,由底層處理;當score>0時,由高層處理。</p>請輸入學產生績<input type="text" id="score"> <input type="button" onClick="test()" value=" 看看結果"><p id="pp"></p></body></html>

下面是其它網友的補充:

javascript中的回調模式:

形如:

function writeCode(callback){    //執行一些事物,    callback();    //...   }    function intrduceBugs(){    //....引入漏洞   }  writeCode(intrduceBugs); 

        我們傳遞函數的應用給writeCode(),讓writeCode在適當的時候來執行它(返回以後調用)

先看一個不怎麼好的例子(後續要對其重構):

//類比尋找頁面中的dom節點,將尋找到的節點存在數組裡面統一返回   //此函數只用於尋找不對dom節點做任何的邏輯處理   var findNodes = function(){    var i = 100000;//大量的迴圈,    var nodes = [];//用於儲存找到的dom節點    var found;    while(i){     i -=1;     nodes.push(found);    }    return nodes;   }    //將尋找找到的dom節點全部隱藏   var hide = function(nodes){    var i = 0,     max = nodes.length;    for(;i<max;i++){ //findNodes後面有括弧代表立即執行,先執行findNodes()然後執行hide()< hide(findNodes()); 執行函數 } ; nodes[i].style.display="none"}上面的方法是低效的,以為hide()必須再次遍曆有findNodes()返回的數組節點,如何避免這種多餘的迴圈呢。   我們不能直接在findNodes中對查詢到的節點進行隱藏(這樣檢索就可修改邏輯耦合了),那麼他就不再是一個通用函數了。   解決方案是用回調模式,可以將節點隱藏邏輯以回呼函數方式傳遞給findNodes()並委託其執行//重構findNodes以接受一個回呼函數    var findNodes = fucntion(callback){     var i = 100000,      nodes = [],      found;     //檢查回呼函數是否可用調用的     if(typeof callback !== 'function'){      callback = false;     }     while(i){      i -= 1;      if(callback){       callback(found);      }      nodes.push(found);     }     return nodes;    }     //回呼函數    var hide = function(node){     node.style.display = 'none ';    }    //找到後續節點並在後續執行中對其進行隱藏  findNodes(hide);//先執行findNodes然後執行hide,當然回呼函數也可以在調用主函數時建立:findNodes(function(node){node.style.display = 'none';});

JS回呼函數

回呼函數可以繼續擴充一個函數的功能,可以是程式非常靈活。
比如:
function showDiv(callback){
$("#div1").show();
callback($("#div1"));
}

showDiv(function($div){
$div.text("hello world");
});
//原本showDiv的功能就是現實一個div,加了callback函數當參數後就可以在執行完show之後改變div中的文字。

一般來說,callback函數用在非同步中的例子比較多,因為在非同步呼叫中,只能通過回呼函數繼續執行某個動作。
例如:
function myThread(callback){
return setTimeout(1000*10,function(){
$("#div").append("<p>hello</p>");//10秒後在div中加一個行,然後在執行callback函數
callback();
});
}
 
什是JS回呼函數

回呼函數就是某個函數執行完畢後執行的函數,沒什麼的啊。比如:
function(callback){
// 代碼
// 以上代碼執行完畢後執行回呼函數
if(typeof callback === "function"){
callback();

}

}
這是因為js中函數可以當做參數直接傳遞進去。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.