在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);
因篇幅问题不能全部显示,请点此查看更多更全内容