日期:2014-05-16  浏览次数:20392 次

js 函数调用的问题
刚学习node.js,有个小问题想请问下大家。


var http = require("http");
http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});  
    response.write("Hello World");  
    response.end();
}).listen(8888);


这是 基本的例子,但我看到也有这样写的:

var http = require("http");
function onRequest(request, response){
       response.writeHead(200, {"Content-Type":"text/plain"});
       response.write("Hellod Word");
       response.end();
}
http.createServer(onRequest).listen(8888);


我想问下 http.createServer(onRequest).listen(8888); 这句代码中调用onRequest函数时为什么没加参数括号啊?
------解决方案--------------------
onRequest 已经定义为一个函数,createServer方法需要一个函数作为参数onRequest 指向函数,只不过两种方式的区别在于 一个传递了匿名函数,一个传递了带有名称的函数 

一旦加上括号,就相当于执行这个函数