当前位置:天才代写 > tutorial > 其他教程 > Node.js 函数

Node.js 函数

2017-11-02 08:00 星期四 所属: 其他教程 浏览:459

Node.js 函数

在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);
 

    关键字:

天才代写-代写联系方式