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) {     http://www.iis7.com/a/lm/fwqdq/  IIS7服務器大全
  someFunction(value);
}
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);ui

相關文章
相關標籤/搜索