學習之前還真不知道 JS 回呼函式怎麼使用及有什麼作用,下面把我在學習回呼函式時整理的例子介紹給各位,有需要了解的同學不妨參考。
回呼函式原理:我現在出發,到了就通知你。這是一個異步流程——「我出發」這個過程(函式執行)中,「你」可以去做任何事;「到了」(函式執行完畢)再「通知你」(回呼)進行後續流程。
例子一,基本方法:
<script language="javascript" type="text/javascript">
function doSomething(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>
例子二,進階方法。使用 call 方法,可以指定回呼時的 this 上下文:
<script language="javascript" type="text/javascript">
function Thing(name){ this.name = name; }
Thing.prototype.doSomething = function(callback){
// 用自己的實例作為上下文呼叫回呼
callback.call(this);
}
function foo(){ alert(this.name); }
var t = new Thing('Joe');
t.doSomething(foo); // 透過 foo 提示 "Joe"
</script>
用 call 傳參數:
<script language="javascript" type="text/javascript">
function Thing(name){ this.name = name; }
Thing.prototype.doSomething = function(callback, salutation){
callback.call(this, salutation);
}
function foo(salutation){ alert(salutation + " " + this.name); }
var t = new Thing('Joe');
t.doSomething(foo, 'Hi'); // 提示 "Hi Joe"
</script>
使用 apply 傳參數(以陣列傳入多個參數):
<script language="javascript" type="text/javascript">
function Thing(name){ this.name = name; }
Thing.prototype.doSomething = function(callback){
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); // 提示 "Hi Joe – 3 2 1"
</script>
再看一個把回呼函式發揮到實戰的例子:把查找節點與處理節點的邏輯分離。原本 hide(findNodes()) 會先遍歷查找、再遍歷隱藏,顯得低效;重構後讓 findNodes 接受一個回呼函式,在查找的過程中直接委托其處理每個節點,避免多餘的迴圈:
// 重構 findNodes 以接受一個回呼函式
var findNodes = function(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(function(node){ node.style.display = 'none'; });
透過把回呼函式傳給主函式、由主函式在恰當時機呼叫,就能實現邏輯的分離與解耦,這正是回呼模式在 JavaScript 中的核心價值。