由于写此篇博客的地点是学校机房,环境较为恶劣,故下方的图片可能会引起不适,请注意前方高能预警!!!有怪莫怪!
node.js的函数
Node.js 中函数的使用与 JavaScript 类似,举例来说,你可以这样做:
function say(word) {
console.log(word);
}
say('Hello');
或者这样:
function say(word) {
console.log(word);
}
function execute(someFunction, value) {
someFunction(value);
}
execute(say, "Hello");
结果会在命令行那里输出hello。
以上第二段代码中,我们把 say 函数作为 execute 函数的第一个变量进行了传递。这里传递的不是 say 的返回值,而是 say 本身!
这样一来, say 就变成了execute 中的本地变量 someFun ,execute 可以通过调用 someFun() (带括号的形式)来使用 say 函数。
当然,因为 say 有一个变量, execute 在调用 someFunction 时可以传递一个say所需要的变量。
匿名函数
我们可以把一个函数作为变量传递。但是我们不一定要绕这个"先定义,再传递"的圈子,我们可以直接在另一个函数的括号中定义和传递这个函数,这就是我们所谓的匿名函数。
匿名函数,匿名函数,顾名思义就是没有名字的函数,一般语法就是
function(变量名){函数的结构}
代码如下:
//非匿名函数,函数名叫execute
function execute(someFun, value) {
someFun(value);
}
//function(word)这个就是匿名函数啦,他没有自己的名字,但他知道自己是个函数
execute(function(word){ console.log(word) }, "Hello");
从HTTP服务器的工作了解匿名函数
我们先贴一段熟悉的代码:
const http = require("http");
//createServer里面的function就是匿名函数
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(3000);
现在解释起来这个东西就简单了,就是我们向createServer函数传递了一个匿名函数。
他也等价于:
const http = require("http");
//有名字的函数,名为onRequest
function onRequest(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
//createServer接收的函数是非匿名函数,名为onRequest,监听的端口号为3000
http.createServer(onRequest).listen(3000);