函数的概念
在JavaScript当中,函数是可以作为另一个函数的参数。
我们可以先定义一个函数,然后传递,也可以在传递参数的地方直接定义函数。
Node中函数的使用与JavaScript类似
匿名函数
function execute(someFunction, value){
someFunction(value);
}
execute(function(word){
console.log(word);
},'Hello');
HTTP服务端的函数传递
// 同样功能不同的实现方式
// 匿名函数
var http = require("http");
http.createServer(function (req, res) {
res.writeHead(200, { "Content-Type": "text/plain" })
res.write("hello world");
res.end();
}).listen(8888);
// 先定义后传递
var http = require("http");
function onRequest(req, res) {
res.writeHead(200, { "Content-Type": "text/plain" })
res.write("hello world");
res.end();
}
http.createServer(onRequest).listen(8888);
两种方式只是写法不一样,实际效果是一样的,看个人习惯。