Misha Moroshko
Misha Moroshko

Reputation: 171341

How to handle wrong constructor arguments in Javascript?

I have a Foo constructor like this:

function Foo(params) {
  this.x = params.x + 5;
  ...  
}

Foo is called like this:

var foo = new Foo(someObject);

I would like to check the contents of params in Foo's constructor, and if something is wrong (e.g. params.x is not a number, or params.y is undefined), I would like foo to be null (which will mean that the Foo object wasn't created).

One option, I guess, is to throw an exception in the constructor and wrap the call for new Foo(someObject) with try..catch (or create a function like makeFoo that does so).

How would you suggest to handle this problem?

Upvotes: 2

Views: 500

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

I would throw the exception. An invalid input is an exceptional condition, throwing an exception makes sense. I wouldn't bother with the makeFoo wrapper; the calling code should handle it.


Re

I would like foo to be null (which will mean that the Foo object wasn't created).

There's no way to make the expression new Foo(...) return null. Normally, the result of the new expression is a reference to the object that was constructed by the new operator and passed into the constructor function as this. The constructor function can override that and return a different object, but it can't do so by returning null. If the constructor function doesn't return anything, or returns something that isn't an object (not including null; null isn't an object [it has its own type, Null], despite the fact that typeof null is "object"), the result of the new expression will be the object created by the new operator. More in Sections 11.2.2 and 13.2.2.

Upvotes: 3

Related Questions