Question

I am trying to understand the following piece of Javascript code:

var Query = function(config, values, callback) {

  // use of "new" optional
  if(!(this instanceof Query)) { return new Query(config, values, callback); }

  ...

};

If someone calls new Query(...), when and why this would not be an instance of Query? Why does this code tests this possibility? What issue does it solve?

Était-ce utile?

La solution

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

Autres conseils

This code is only preventing a bug that could arise if somebody forgets to add new : it works the same in that case.

I've frequently seen this pattern. In my opinion it's bad : you shouldn't try to prevent bad misuses of your API, especially as it might make the user code more obscure for somebody who knows new. It's not like if new were an especially advanced JavaScript feature... It's better to fail than to let various seemingly invalid user codes be magically valid.

this code makes it possible to use Query constructor with new and without new statements, if you will use

var bla = Query();

this will poing to window, it'll be checked inside the Query function and new Query() will be called, this time this instanceof Query will return true

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top