node. js function
In JavaScript, a function can be used as a parameter to another function. We can define a function first, then pass it, or we can define the function directly where the parameter is passed.
The use of functions in node. JS is similar to JavaScript, for example, you can do this:
functionSay(word) { Consolelog (word}function Execute ( Span class= "PLN" >somefunction, Value) Span class= "pun" >{ Somefunction (value}execute (say , "Hello"
In the above code, we pass the say function as the first variable of the Execute function. The return value here is not say, but the say itself!
In this way, say becomes the local variable someFunction in Execute, and execute can use the say function by calling SomeFunction () (in the form of parentheses).
Of course, because say has a variable, execute can pass such a variable when calling SomeFunction.
anonymous functions
We can pass a function as a variable. But we don't have to go around this "define first, then pass" circle, and we can define and pass the function directly in the parentheses of another function:
function Execute ( Span class= "PLN" >somefunction, Value) Span class= "pun" >{ Somefunction (value}execute (function (word Console. Logword }, "Hello"
We directly define the function we are going to pass to execute, where execute accepts the first argument.
In this way, we don't even have to name the function, which is why it is called an anonymous function.
function passing is how to get the HTTP server to work
With this knowledge, let's take a look at our simple and not simple HTTP server:
Varhttp= Require("http");http.Createserver(function(Request, Response) {. Writehead (200, { "Content-type" : "Text/plain" Response. "Hello World" response end (); listen8888
Now it should look a lot clearer: we passed an anonymous function to the Createserver function.
This code can also be used to achieve the same purpose:
Varhttp= Require("http");functionONrequest(Request,Response) {Responsewritehead (200, { "Content-type" : }); Response. "Hello World" response end (); }http.onrequest8888
node. js function