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?
I would throw the exception. An invalid input is an exceptional condition, throwing an exception makes sense. I wouldn’t bother with the
makeFoowrapper; the calling code should handle it.Re
There’s no way to make the expression
new Foo(...)returnnull. Normally, the result of thenewexpression is a reference to the object that was constructed by thenewoperator and passed into the constructor function asthis. The constructor function can override that and return a different object, but it can’t do so by returningnull. If the constructor function doesn’t return anything, or returns something that isn’t an object (not includingnull;nullisn’t an object [it has its own type,Null], despite the fact thattypeof nullis"object"), the result of thenewexpression will be the object created by thenewoperator. More in Sections 11.2.2 and 13.2.2.