Node.js 回调函数,匿名函数,函数传递

Nodejs函数

在js中,函数可以作为另一个函数的参数

function say(word) {
  console.log(word);
}

// 第一个参数someFunction用来传递函数类型的参数
function execute(someFunction, value) {
  someFunction(value);
}

// execute函数接收了say函数作为参数
execute(say, "Hello");

匿名函数

函数作为变量(参数)传递的时候,不一定要预先定义

可以在另一个函数括号中定义和传递,因为不需要起名字,所以叫做匿名函数

function execute(someFunction, value) {
  someFunction(value);
}

// 临时定义了execute函数的第一个参数
execute(function(word){ console.log(word) }, "Hello");

函数传递和HTTP服务器

var http = require("http");

// createServer函数的第一个参数也是一个临时定义的函数(匿名函数)
http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);

以上代码等价于

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);
posted @ 2021-10-28 14:37  景北斗  阅读(427)  评论(0编辑  收藏  举报