综合技术

sending objects to a callback function as a prameter- nodejs

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

Laracon Online 2018 Early Bird Registration Reminder

上一篇

Uber需等到明年4月底才能开始就伦敦执照吊销进行上诉

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
sending objects to a callback function as a prameter- nodejs

长按储存图像,分享给朋友