[Node.js]函数

摘要

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

一个例子

function sayHello(content){
    console.log(content);
};
function execute(func,value){
    func(value);
};
execute(sayHello,"Hello function wolrd");

从上面的代码,我们可以看到我们把函数sayHello函数作为execute函数的第一个参数进行传递。这里返回的不是sayHello的返回值,而是sayHello本身。这样以来,sayHello就成为了execute中的本地变量func,execute可以通过调用func来使用sayHello函数。

sayHello函数有个参数,在使用execute调用sayHello函数时,可以传递一个变量。

匿名函数

我们可以把一个函数作为变量直接传递。如上面的例子中,我们可以不先定义函数sayHello,直接在execute函数中传递一个没有名称的匿名函数。

function execute(func,value){
    func(value);
};
execute(function(word){
    console.log(word);
},"Hello function wolrd");

函数传递是如何让HTTP服务器工作的

有了上面的基础,我们来看看Http服务器中的函数。

var http=require("http");
http.createServer(function(request,response){
    response.writeHead(200,{"Content-Type":"text/plain"});
    response.write("Hello my http world.");
    response.end();
}).listen(4455,"127.0.0.1");

上面的代码,我们在创建http服务器的函数createServer中传递了一个匿名函数,当然,我们也可以定一个函数,然后传递给createServer函数,达到同样的目的。

学习资料

http://www.runoob.com/nodejs/nodejs-function.html

原文地址:https://www.cnblogs.com/wolf-sun/p/6362263.html