Node.js 第十章- 函数

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

如下:

function say(word) {

   console.log(word)

}

function execute(someFunction, value) {

 someFunction(value);

}

execute(say, "Hello");

以上代码中,我们把say函数作为execute函数的第一个变量进行了传递。

这里传递的不是say的返回值,而是say本身。

二,匿名函数

我们可以把一个函数作为变量传递。

我们可以直接在另外一个函数的括号中定义和传递这个函数。

function execute(someFunction, value) {

    someFunction(value);

}

execute(function(word){console.log(word)}, 'hello');

用这种方式,函数都不用起名字,这叫匿名函数。

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

1.

换一种写法,以上是传递了一个匿名函数。

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

猜你喜欢

转载自blog.csdn.net/u014085502/article/details/85244702