在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