This is JavaScript pattern known as "Self-Invoking Constructor" (check JavaScript Patterns).
If the function Query
is called:
Query();
then this
won't be instance of Query.
The code makes sure that no matter how Query
is called new object, created with the constructor function Query
, will be returned.
For example:
function foo() {
}
console.log(foo()); //undefined
console.log(foo.call(null)); //undefined
console.log(foo.apply(null)); //undefined
console.log(new foo()); //object, instance of foo
but if:
function foo() {
if (!(this instanceof foo)) {
return new foo();
}
}
console.log(foo()); //object, instance of foo
console.log(foo.call(null)); //object, instance of foo
console.log(foo.apply(null)); //object, instance of foo
console.log(new foo()); //object, instance of foo