"this" inside a javascript function
<p>This is a newbie query. I went through few similar posts, but they are not helping me enough. This post has 2 queries, but am putting together because their root seems the same.</p>

<p>I came across the following code snippet :</p>

<pre><code>var Server = module.exports.Server = function Server(listener) {
  if (!(this instanceof Server)) return new Server(listener);
  //other code
}

module.exports.createServer = function(listener) {
  return new Server(listener);
};
</code></pre>

<p>I am unable to understand the use of  <code>if (!(this instanceof Server))  ;</code> when can this not point to Server here ?</p>

<p>I tried putting a quick test for this :</p>

<pre><code>var createTest = function(){
    console.log(this.toString());
    return new Test();
};

var Test = function Test(){
    console.log(this instanceof Test);
    console.log(this.toString());
    if (!(this instanceof Test)) 
    {
        return new Test();
    }
}

var tester = createTest();
</code></pre>

<p>which outputs :</p>

<pre><code>[object global]
true
[object Object]
</code></pre>

<p>which further confuses me over why this.toString prints [object Object] - shouldn't it be [object Test] ?</p>

<p>Thanks !</p>
