sending objects to a callback function as a prameter- nodejs

综合技术 2017-12-11 阅读原文

i am implementing a http server
for some project.

i have an HttpServer
object that i created that contains in it a server (net module)

this server contains allot of info, and i want to pass it as parameter to the callback functions. like you would do with " setTimeout
"

var time=setTimeout(function(**a**){do somthing}, 2000, **someObject**);

i tried doing somthing like that in my code but it does not recognize the parameter i passed as an object

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

any one have any idea why it does not recgonize the paramter sent?

thank you

Problem courtesy of: kakush

Solution

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

Solution courtesy of: Headshota

Node.js Recipes

责编内容by:Node.js Recipes阅读原文】。感谢您的支持!