我正在为某个项目实施http server
。
我创建了一个HttpServer
对象,其中包含一个服务器(网络模块)
此服务器包含大量信息,我想将其作为参数传递给回调函数。就像你使用“setTimeout
”
var time=setTimeout(function(**a**){do somthing}, 2000, **someObject**);
我尝试在我的代码中执行类似的操作,但它无法识别我作为对象传递的参数
var net = require('net');
function HttpServer(port){
this.port=port;
}
HttpServer.prototype.start = function (){
console.log("starting the server");
this.server = net.createServer(function (socket,server) {
console.log("my port is: "+server.port)
socket.on('data',function(dat){ });
},this);
//i am trying to send to the createserver callback function
//the parameter 'this' that actually is an HttpServer
//and the callback function secives it as 'server'
//when i run the program i get an error that server is
//undefiend and therefor does not have a member port
this.server.listen(this.port);
}
var httpserver= new HttpServer(4444);
httpserver.start();
为什么它无法识别发送的参数?
答案 0 :(得分:2)
var net = require('net');
function HttpServer(port){
this.port=port;
}
HttpServer.prototype.start = function (){
console.log("starting the server");
var that = this; //Store this to that variable
this.server = net.createServer(function (socket, server) {
console.log('Server port is: ' + that.port); // Use that in an anonymous function
socket.on('data',function(dat){ });
});
this.server.listen(this.port);
}
var httpserver= new HttpServer(4444);
httpserver.start();