top
Loading...
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);
}
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);
北斗有巢氏 有巢氏北斗