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.
I came across the following code snippet :
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);
};
I am unable to understand the use of if (!(this instanceof Server)) ; when can this not point to Server here ?
I tried putting a quick test for this :
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();
which outputs :
[object global]
true
[object Object]
which further confuses me over why this.toString prints [object Object] - shouldn't it be [object Test] ?
Thanks !
Testobject? Just a guess.