gpt4 book ai didi

javascript - 将对象作为参数发送到回调函数-nodejs

转载 作者:行者123 更新时间:2023-12-02 19:55:28 25 4
gpt4 key购买 nike

我正在为某个项目实现一个http 服务器

我创建了一个 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();

为什么无法识别发送的参数?

最佳答案

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

关于javascript - 将对象作为参数发送到回调函数-nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8694232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com