1. 程式人生 > >Node.js 函式

Node.js 函式

Node.js 函式
在JavaScript中,一個函式可以作為另一個函式接收一個引數。我們可以先定義一個函式,然後傳遞,也可以在傳遞引數的地方直接定義函式。
Node.js中函式的使用與Javascript類似,舉例來說,你可以這樣做:
function say(word) {
  console.log(word);
}

function execute(someFunction, value) {
  someFunction(value);
}

execute(say, "Hello");
以上程式碼中,我們把 say 函式作為execute函式的第一個變數進行了傳遞。這裡返回的不是 say 的返回值,而是 say 本身!
這樣一來, say 就變成了execute 中的本地變數 someFunction ,execute可以通過呼叫 someFunction() (帶括號的形式)來使用 say 函式。
當然,因為 say 有一個變數, execute 在呼叫 someFunction 時可以傳遞這樣一個變數。
。。。
匿名函式
我們可以把一個函式作為變數傳遞。但是我們不一定要繞這個"先定義,再傳遞"的圈子,我們可以直接在另一個函式的括號中定義和傳遞這個函式:
function execute(someFunction, value) {
  someFunction(value);
}http://www.iis7.com/a/lm/gjcpmcx/
execute(function(word){ console.log(word) }, "Hello");
我們在 execute 接受第一個引數的地方直接定義了我們準備傳遞給 execute 的函式。
用這種方式,我們甚至不用給這個函式起名字,這也是為什麼它被叫做匿名函式 。
。。。
函式傳遞是如何讓HTTP伺服器工作的
帶著這些知識,我們再來看看我們簡約而不簡單的HTTP伺服器:
var http = require("http");
http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);
現在它看上去應該清晰了很多:我們向 createServer 函式傳遞了一個匿名函式。
用這樣的程式碼也可以達到同樣的目的:
var http = require("http");
function onRequest(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}
http.createServer(onRequest).listen(8888);