nodejs学习(三)函数
一.Node.js 函数
在 JavaScript中,一个函数可以作为另一个函数的参数。我们可以先定义一个函数,然后传递,也可以在传递参数的地方直接定义函数。
Node.js 中函数的使用与 JavaScript 类似,举例来说,你可以这样做:
1 2 3 4 5 6 7 8 9 10 11 12 13 | //常规函数 function say(name) { console.log( "hello" + " " + name) } //函数作为值传递 function execute(someFunction, value) { someFunction(value) } execute(say, "tom" ) |
以上代码中,我们把 say 函数作为 execute 函数的第一个变量进行了传递。这里传递的不是 say 的返回值,而是 say 本身!
这样一来, say 就变成了execute 中的本地变量 someFunction ,execute 可以通过调用 someFunction() (带括号的形式)来使用 say 函数。
当然,因为 say 有一个变量, execute 在调用 someFunction 时可以传递这样一个变量。
二.匿名函数
我们可以把一个函数作为变量传递。但是我们不一定要绕这个"先定义,再传递"的圈子,我们可以直接在另一个函数的括号中定义和传递这个函数:
1 2 3 4 5 | function execute(someFunction, value) { someFunction(value); } execute( function (word){ console.log(word) }, "Hello" ); |
我们在 execute 接受第一个参数的地方直接定义了我们准备传递给 execute 的函数。
用这种方式,我们甚至不用给这个函数起名字,这也是为什么它被叫做匿名函数 。
三.函数传递是如何让HTTP服务器工作的
1 2 3 4 5 6 7 | 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 函数传递了一个匿名函数。
用这样的代码也可以达到同样的目的:
1 2 3 4 5 6 7 8 9 | 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); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
2019-03-26 关于字体反爬的思路(猫眼电影)
2019-03-26 路飞学城搭建值前后端结合