javascript构造函数+ node js createServer

时间:2014-05-31 13:47:03

标签: javascript node.js

我试图在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);
    });
};

问题是,在handleNewConnection函数中,我试图使用我的staticServerObj变量(如:staticServerObj.port)并且它是未定义的, 此外,当我尝试以这种方式记录服务器对象时:

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

我得到了这个结果:

{ 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' }

任何想法?

1 个答案:

答案 0 :(得分:1)

你有一个范围问题。 this内的createServer()不再指向服务器对象。要解决此问题,请保存对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);
    });
};

或使用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 );
}