【发布时间】:2012-11-28 21:52:13
【问题描述】:
我正在node.js 中编写http 服务器。
Server 对象有几个字段,应根据请求发送给客户端。这就是为什么我需要将status() 传递给router.route() 的原因——因此可以从内部调用它(在解析请求之后)并返回更新变量值。问题是当status() 被调用时,它不会打印字段值,而是对象字面量。
构造函数Server如下:
this.server = net.createServer(connectionHandler);
this.resourceMap = resourceMap;
this.rootFolder = rootFolder;
this.isStarted = false;
this.startedDate = undefined;
this.port = undefined;
this.numOfCurrentRequests = 0;
function status() {
return {
"isStarted" : this.isStarted,
"startedDate" : this.startedDate,
"port" : this.port,
"resourceMap" : this.resourceMap,
};
}
function connectionHandler(socket) {
console.log('server connected');
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
socket.setEncoding('utf8');
socket.on('data',function(data) {
this.numOfCurrentRequests += 1;
router.route(status,data,socket,handle,resourceMap,rootFolder);
});
}
this.startServer = function(port) {
this.port = port;
this.isStarted = true;
this.startedDate = new Date().toString();
this.server.listen(port, function() {
console.log('Server bound');
});
}
}
当从router.route() 中调用状态时,我得到
function status() {
return {
"isStarted" : this.isStarted,
"startedDate" : this.startedDate,
"port" : this.port,
"resourceMap" : this.resourceMap,
};
}
我理解函数的方式是变量,因此按值传递。有什么办法可以解决我的问题?
谢谢
【问题讨论】:
-
我想你只需要改变这一行:router.route(status,data,socket,handle,resourceMap,rootFolder);到 router.route(status(),data,socket,handle,resourceMap,rootFolder);
-
我试了一下,结果是[object,object]
-
啊,它正在显示。也许 JSON.stringify(status()) 会让它看起来更具可读性
-
我试试吧。但是函数不是像我写的那样按值传递吗?
-
这就是你使用 () 执行函数的原因——当你得到 JavaScript 对象的 [object, object] 时。对其进行字符串化应该使其在 Bowser 中可读。
标签: node.js function pointers arguments