函數就是對象,因此他們能夠做爲一個參數傳遞給其它函數;node
當你將introduceBugs()做爲一個參數傳遞給writeCode(),而後在某個時間點,writeCode()有可能執行(調用)introduceBugs();編程
這種狀況下,introduceBugs()被稱爲回調函數(callback function)或簡稱爲回調(callback:):數組
function writeCode(callback) { // do something... callback(); // ... } function introduceBugs() { // ... make bugs } writeCode(introduceBugs);
注意introduceBugs()做爲一參數傳遞給writeCode()是沒有使用括號的;瀏覽器
使用括號會當即執行函數,然而在這種狀況下,咱們但願的是隻傳遞一個指向函數的引用,讓writeCode()在適當的時候去執行;app
var findNodes = function() { var i = 100000, // big, heavy loop nodes = [], // stores the result found; // the next node found while (i) { i -= 1; // complex logic here... nodes.push(found); } return nodes; };
var hide = function(nodes) { var i = 0, max = nodes.length; for (; i < max; i += 1) { nodes[i].style.display = "none"; } }; // executing the functions hide(findNodes());
// refactored findNodes() to accept a callback var findNodes = function(callback) { var i = 100000, nodes = [], found; // check if callback is callable if (typeof callback !== "function") { callback = false; } while (i) { i -= 1; // complex logic here... // now callback: if (callback) { callback(found); } nodes.push(found); } return nodes; };
// a callback function var hide = function(node) { node.style.display = "none"; }; // find the nodes and hide them as you go findNodes(hide);
// passing an anonymous callback findNodes(function (node) { node.style.display = "block"; });
在前面這個例子中,回調函數執行的部分可能像:dom
callback(parameters);
var myapp = {}; myapp.color = "green"; myapp.paint = function(node) { node.style.color = this.color; };
findNodes()函數作了相似下面的事:異步
var findNodes = function(callback) { // ... if (typeof callback === "function") { callback(found); } // ... };
findNodes(myapp.paint, myapp);
緊跟着,咱們須要去修改findNodes()去綁定(bind)傳遞進來的對象:ide
var findNodes = function(callback, callback_obj) { //... if (typeof callback === "function") { callback.call(callback_obj, found); } // ... };
findNodes(myapp.paint, myapp);
會變成:函數
findNodes("paint", myapp);
那麼findNodes()可能會作一些事,就像下面幾行:oop
var findNodes = function(callback, callback_obj) { if (typeof callback === "string") { callback = callback_obj[callback]; } //... if (typeof callback === "function") { callback.call(callback_obj, found); } // ... };
document.addEventListener("click", console.log, false);
var thePlotThickens = function () { console.log('500ms later...'); }; setTimeout(thePlotThickens, 500);