简体   繁体   English

(Javascript)为什么函数不带参数

[英](Javascript) Why doesn't function take parameters

This is a NodeJS stuff, the code is: 这是一个NodeJS的东西,代码是:

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);

My question is how come in the last line, the function onRequest doesn't take parameters.. I'm new to Javascript but isn't onRequest supposed to take 2 parameters as defined in the function? 我的问题是如何进入最后一行,函数onRequest不带参数..我是Javascript的新手,但是不是onRequest应该采取函数中定义的2个参数? Can anyone help me please? 有人可以帮我吗? I've been stuck for an hour :( 我被困了一个小时:(

You're not actually calling the method. 你实际上并没有调用这个方法。 You're telling createServer what its requestListener callback function is. 你告诉createServer它的requestListener回调函数是什么。

From the node.js documentation ( http://nodejs.org/api/http.html#http_http_createserver_requestlistener ): 从node.js文档( http://nodejs.org/api/http.html#http_http_createserver_requestlistener ):

http.createServer([requestListener]) http.createServer([requestListener])

Returns a new web server object. 返回一个新的Web服务器对象。

The requestListener is a function which is automatically added to the 'request' event. requestListener是一个自动添加到'request'事件的函数。

Execution of the onRequest function takes 2 parameters. 执行onRequest函数需要2个参数。

Your last line: 你的最后一行:

http.createServer(onRequest).listen(8888);

does not actually execute onRequest, though I can see why you would think it does. 实际上并没有执行onRequest,虽然我可以理解为什么你会认为它。 It passes a reference to the onRequest function to the http.createServer function / method. 它将对onRequest函数的引用传递给http.createServer函数/方法。

createServer will save a pointer to your onRequest function and then when a request comes into the server, it will execute onRequest. createServer将保存指向onRequest函数的指针,然后当请求进入服务器时,它将执行onRequest。 That execution will include a request and response argument. 该执行将包括请求和响应参数。

For details, this article gives a fairly straightforward and concise explanation of this pattern, known as callbacks. 有关详细信息,本文对此模式提供了相当简单明了的解释,称为回调。 It typically goes with asynchronous programming, but doesn't have to. 它通常与异步编程一起使用,但不一定如此。

http://recurial.com/programming/understanding-callback-functions-in-javascript/ http://recurial.com/programming/understanding-callback-functions-in-javascript/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM