回調函數是什麼在學習之前還真不知道js回調函數怎麼使用及作用了,下面本文章把我在學習回調函數例子給各位同學介紹一下吧,有需了解的同學不防進入參考。
回調函數原理:
我現在出發,到了通知你”
這是一個異步的流程,“我出發”這個過程中(函數執行),“你”可以去做任何事,“到了”(函數執行完畢)“通知你”(回調)進行之後的流程
例子
1.基本方法
<script language="javascript" type="text/javascript">
function doSomething(callback) {
// …
// Call the callback
callback('stuff', 'goes', 'here');
}
function foo(a, b, c) {
// I'm the callback
alert(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 context
callback.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 context
callback.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 context
callback.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';});