简体   繁体   English

JavaScript构造函数+节点js createServer

[英]javascript constructor + node js createServer

Im trying to wrap node js server in JS object, In order to do that, I wrote this constructor: 我试图将节点js服务器包装在JS对象中,为此,我编写了以下构造函数:

function staticServerObj (rootFolder) {
    this.rootFolder = rootFolder;
    this.port = null;
    this.isStarted = false;
    this.startedData = null;
    this.numOfCurrentRequests = 0;
    this.numOfAllRequests = 0;
    this.numOfSuccesfulRequest = 0;

    this.serverObj = net.createServer(function (socket) {
        handleNewConnection(this, socket);
    });
};

The problem is, in handleNewConnection function, Im trying to use my staticServerObj vars (like: staticServerObj.port) and it's undefined, Furthermore, when I try to log the server object in that way: 问题是,在handleNewConnection函数中,我试图使用我的staticServerObj变量(例如:staticServerObj.port),并且它是未定义的,此外,当我尝试以这种方式记录服务器对象时:

function handleNewConnection(server, socket) {
    console.log(server);
}

Im getting this result: 我得到这个结果:

{ domain: null,
  _events: { connection: [Function] },
  _maxListeners: 10,
  _connections: 1,
  connections: [Getter/Setter],
  _handle: 
   { fd: 12,
     writeQueueSize: 0,
     onconnection: [Function: onconnection],
     owner: [Circular] },
  _usingSlaves: false,
  _slaves: [],
  allowHalfOpen: false,
  _connectionKey: '4:0.0.0.0:1234' }

Any Ideas? 有任何想法吗?

You have a scoping problem. 您有范围问题。 The this inside your createServer() does not point to the server object anymore. createServer()中的this不再指向服务器对象。 To solve this either save a reference to the staticServerObj like this: 要解决此问题, staticServerObj像这样保存对staticServerObj的引用:

function staticServerObj (rootFolder) {
    this.rootFolder = rootFolder;
    this.port = null;
    this.isStarted = false;
    this.startedData = null;
    this.numOfCurrentRequests = 0;
    this.numOfAllRequests = 0;
    this.numOfSuccesfulRequest = 0;

    var that = this;

    this.serverObj = net.createServer(function (socket) {
        handleNewConnection(that, socket);
    });
};

or use bind() and have access to the this reference inside your function: 或使用bind()并可以在函数内访问this引用:

function staticServerObj (rootFolder) {
    this.rootFolder = rootFolder;
    this.port = null;
    this.isStarted = false;
    this.startedData = null;
    this.numOfCurrentRequests = 0;
    this.numOfAllRequests = 0;
    this.numOfSuccesfulRequest = 0;

    var that = this;

    this.serverObj = net.createServer( handleNewConnection.bind( this ) );
};

function handleNewConnection(socket) {
   // your former server variable can now be accessed using `this`
    console.log( this );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM