文章永久连接:https://tech.souyunku.com/?p=5442
JavaScript 中的函数是一等公民,一个函数可以作为另一个函数的参数。
我们既可以先定义一个函数,然后作为参数传递给另一个函数,也可以直接在传递参数的地方定义一个匿名函数
因为 Node.js 基于 JavaScript ,所以在 Node.js 中定义和使用函数和 JavaScript 中一样
/*
* filename: main.js
* author: 搜云库技术团队(tech.souyunku.com)
* Copyright © 2015-2065 tech.souyunku.com. All rights reserved.
*/
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 时可以传递这样一个参数
运行以上 Node.js 范例,输出结果如下
$ node main.js
Hello
匿名函数
JavaScript 将函数作为参数进行传递,不一定要遵循 “先定义,再传递” 的原则,可以直接在传递的时候定义函数,这种函数我们称之为 匿名函数
用这种方式,我们甚至不用这种参数函数起名字,这也是为什么它被叫做匿名函数
使用匿名函数,我们可以将上面的范例改写如下
/*
* filename: main.js
* author: 搜云库技术团队(tech.souyunku.com)
* Copyright © 2015-2065 tech.souyunku.com. All rights reserved.
*/
function execute(someFunction, value) {
someFunction(value);
}
execute(function(word){ console.log(word) }, "Hello");
我们在 execute 接受第一个参数的地方直接定义了传递给 execute 的函数
运行以上 Node.js 脚本,输出结果如下
$ node main.js
Hello
函数参数传递是如何让 HTTP 服务工作的
使用函数作为参数,我们可以把本来很复杂的逻辑整理的清楚明白
/*
* filename: main.js
* author: 搜云库技术团队(tech.souyunku.com)
* Copyright © 2015-2065 tech.souyunku.com. All rights reserved.
*/
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
这段代码使用了匿名函数,而且已经够清楚明白了
当然,我们也可以把上面的代码改写成如下的格式
/*
* filename: main.js
* author: 搜云库技术团队(tech.souyunku.com)
* Copyright © 2015-2065 tech.souyunku.com. All rights reserved.
*/
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);
干货推荐
附录:Node.js 教程:系列文章
- 一、Node.js 基础教程
- 二、Node.js 环境配置
- 三、Node.js 创建第一个应用
- 四、Node.js NPM 使用介绍
- 五、Node.js 使用淘宝 NPM 镜像
- 六、Node.js REPL ( 交互式解释器 )
- 七、Node.js 回调函数
- 八、Node.js 事件循环
- 九、Node.js EventEmitter
- 十、Node.js Buffer(缓冲区)
- 十一、Node.js Stream (流)
- 十二、Node.js 模块系统
- 【当前读到】十三、Node.js 函数
- 十四、Node.js 开发 URL 路由
- 十五、Node.js 全局对象
- 十六、Node.js 常用工具
- 十七、Node.js 文件系统( fs 模块 )
- 十八、Node.js GET-POST 请求
- 十九、Node.js 内置模块
- 二十、Node.js WEB 模块
- 二十一、Node.js Express 框架
- 二十二、Node.js RESTful API
- 二十三、Node.js 多进程
- 二十四、Node.js JXcore 打包
- 二十五、Node.js 访问 MySQL 数据库
- 二十六、Node.js 访问 MongoDB
- 二十七、Node.js OS 模块
- 二十八、Node.js DNS 模块
- 二十九、Node.js Domain 模块
- 三十、Node.js Path 模块
- 三十一、Node.js Net 模块