函数的概念

在JavaScript当中,函数是可以作为另一个函数的参数。
我们可以先定义一个函数,然后传递,也可以在传递参数的地方直接定义函数。
Node中函数的使用与JavaScript类似

匿名函数

  1. function execute(someFunction, value){
  2. someFunction(value);
  3. }
  4. execute(function(word){
  5. console.log(word);
  6. },'Hello');

HTTP服务端的函数传递

  1. // 同样功能不同的实现方式
  2. // 匿名函数
  3. var http = require("http");
  4. http.createServer(function (req, res) {
  5. res.writeHead(200, { "Content-Type": "text/plain" })
  6. res.write("hello world");
  7. res.end();
  8. }).listen(8888);
  9. // 先定义后传递
  10. var http = require("http");
  11. function onRequest(req, res) {
  12. res.writeHead(200, { "Content-Type": "text/plain" })
  13. res.write("hello world");
  14. res.end();
  15. }
  16. http.createServer(onRequest).listen(8888);

两种方式只是写法不一样,实际效果是一样的,看个人习惯。