Node.js函數

Node.js函數服務器

在JS語言中,一個函數能夠做爲另外一個函數的參數。能夠先定義在傳遞,也能夠直接使用匿名函數進行傳遞。函數

Node.js中函數的使用與JS相似,基本差很少。ui

下面寫兩個例子。code

先定義函數,在進行傳遞it

// 定義函數say
function say(val){
    console.log(val)
}
// 咱們將say函數做爲execute第一個參數進行傳遞,這樣以來,say函數就變成了execute中的本地變量someFunction
// exectue能夠經過調用someFunction()來使用say函數,say函數有一個變量,在調用的時候咱們能夠傳遞一個變量。
function execute(someFunction, val) {
    someFunction(val)
}
execute(say,'思否')

這個例子就是先定義函數,而後將定義的函數做爲參數給另外一個函數使用。io

還有一種就是直接使用匿名函數console

function execute(somefunction, val) {
    somefunction(val)
}
execute(function(val){console.log(val)}, '思否')

這種方式就是直接使用匿名函數進行傳遞,咱們在execute接收第一個參數的地方直接定義了咱們準備傳參的函數。function

兩種方式均可以,相比較先定義在傳遞,匿名函數寫起來更簡潔,若是有一些不須要重複調用的場景,能夠使用這種方式。匿名函數

瞭解函數傳遞之後,咱們在來看函數傳遞如何讓HTTP服務器工做的。require

// 匿名函數傳遞
const http = require('http')

http.createServer((request , response) => {
    response.writeHead(200, {'Content-Type': 'text/plain'})
    response.write('Hello World')
    response.end()
}).listen(8888)

http.createServer方法中第一個參數咱們直接以匿名函數的方式直接書寫。

const http = require('http')
// 先定義在傳遞
function onRequest(request, response) {
    response.writeHead(200,{'Content-Type': 'text/plain'})
    response.write('Hello sifou.com')
    response.end()
}
http.createServer(onRequest).listen(8888)

這段代碼咱們先定義函數onRequest,而後在進行傳遞。兩種方法均可以

相關文章
相關標籤/搜索