Benson
Benson

Reputation: 275

node net.js Server()

I checked the createServer() function in net.js:

exports.createServer = function() {
return new Server(arguments[0], arguments[1]);
};

I checked the source code of Server() function in net.js and found that

function Server(/* [ options, ] listener */) {
  if (!(this instanceof Server)) return new Server(arguments[0], arguments[1]);
  events.EventEmitter.call(this);

  var self = this;
  // ......
}

When we call the createServer() function, that function will call new Server(). And inside the Server() function, since this is not an instance of Server, it will call new Server() again. Based on my understanding, the new Server() function will fall into an infinite loop since it keeps calling new Server(). Could someone please explain what I am wrong here?

If Quentin is right, then the if statement can never be true since new Server() has been called in the createServer() function.

Upvotes: 1

Views: 123

Answers (2)

Trevor Norris
Trevor Norris

Reputation: 21119

This is a very common pattern in JavaScript. Take the following:

function MyInst(a, b) {
  this.a = a;
  this.b = b;
}

var inst = MyInst(a, b);

You will have effectively appended the properties a and b to the global Object. So instead you have a conditional to check if the call is a proper constructor call:

function MyInst(a, b) {
  if (!(this instanceof MyInst))
    return new MyInst(a, b);
  this.a = a;
  this.b = b;
}

// Now I can be lazy and not use "new"
var inst0 = MyInst(a, b);
// Or I can still use it properly
var inst1 = new MyInst(a, b);

The same thing is being done in net.Server(). Basically protecting people from themselves and always making sure the object context is an instance of itself.

Upvotes: 0

Quentin
Quentin

Reputation: 944441

There's an if statement before the return new Server statement.

It looks like it is there to recover from people calling the Server function without doing as as a constructor function (i.e. with new).

Upvotes: 1

Related Questions