2

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?

1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.