Node.js 教程
- 第1节:Node.js 教程
- 第2节:Node.js 安装配置
- 第3节:Node.js 创建第一个应用
- 第4节:Node.js NPM 使用介绍
- 第5节:Node.js REPL(交互式解释器)
- 第6节:Node.js 回调函数
- 第7节:Node.js 事件循环
- 第8节:Node.js EventEmitter
- 第9节:Node.js Buffer(缓冲区)
- 第10节:Node.js Stream(流)
- 第11节:Node.js 模块系统
- 第12节:Node.js 函数
- 第13节:Node.js 路由
- 第14节:Node.js 全局对象
- 第15节:Node.js 常用工具util
- 第16节:Node.js 文件系统
- 第17节:Node.js GET/POST请求
- 第18节:Node.js 工具模块
- 第19节:Node.js Web 模块
- 第20节:Node.js Express 框架
- 第21节:Node.js RESTful API
- 第22节:Node.js 多进程
- 第23节:Node.js JXcore 打包
- 第24节:Node.js 连接 MySQL
- 第25节:Node.js 连接 MongoDB
- 第26节:关于 Node.js
- 第27节:Node.js 示例
- 第28节:Node.js 断言测试
- 第29节:Node.js 事件
- 第30节:Node.js Punycode
- 第31节:Node.js Buffer
- 第32节:Node.js 文件系统
- 第33节:Node.js Query Strings
- 第34节:Node.js C/C++ 插件
- 第35节:Node.js 逐行读取
- 第36节:Node.js 全局对象
- 第37节:Node.js 子进程
- 第38节:Node.js REPL
- 第39节:Node.js HTTP
- 第40节:Node.js 集群
- 第41节:Node.js Smalloc
- 第42节:Node.js HTTPS
- 第43节:Node.js 控制台
- 第44节:Node.js 模块
- 第45节:Node.js 加密
- 第46节:Node.js 流
- 第47节:Node.js 网络
- 第48节:Node.js 调试器
- 第49节:Node.js 字符串解码器
- 第50节:Node.js 系统
- 第51节:Node.js DNS
- 第52节:Node.js 定时器
- 第53节:Node.js 路径
- 第54节:Node.js 域
- 第55节:Node.js TLS/SSL
- 第56节:Node.js 进程
- 第57节:Node.js TTY
- 第58节:Node.js UDP/Datagram
- 第59节:Node.js URL
- 第60节:Node.js 实用工具
- 第61节:Node.js 虚拟机
- 第62节:Node.js ZLIB
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);