Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should a JavaScript constructor return if it fails?

If I have a javascript class which cannot be instantiated what should the constructor return that I can test for. The constructor always returns an object so I cannot return null if the constructor fails.

function SomeClass(id) {   if(typeof(id) === 'number' {     // This is good     this.id = id;   } else {     // This is bad     // This return is ignored and an empty object is returned     return null;   } }  var a = new SomeClass('badParam'); if(a){   // is true even though the class expects a number. }  // Could use this check if(a.id !== undefined){   // Do some stuff } 

but it seems there should be a better way.

like image 259
oenpelli Avatar asked Mar 01 '11 01:03

oenpelli


People also ask

What does JavaScript constructor return?

Return from constructors Usually, constructors do not have a return statement. Their task is to write all necessary stuff into this , and it automatically becomes the result. But if there is a return statement, then the rule is simple: If return is called with an object, then the object is returned instead of this .

What should be returned from a constructor?

A constructor doesn't return anything.

Can a constructor return undefined?

When strictNullChecks compiler option is set, constructors can not return undefined (or null ). The request is to allow marking a constructor as "failable", which will negate the strictNullChecks for that constructor, adding undefined to the possible return type of the constructor.

Can a constructor be empty JavaScript?

In JavaScript, the Constructor method is invoked when you create an instance of a class. It is also used to initialize objects within a class. However, JavaScript will automatically create and execute an empty constructor if you have not defined any constructor method for a class.


2 Answers

It is probably best to throw an exception to notify the caller that the initialization failed and to take appropriate action.

Return codes are fine, but for the most part there is no motivation for the caller to implement the checks on the return code.

My advice is to break hard and break soon. This will make contract violations very evident during testing.

like image 173
Slappy Avatar answered Sep 23 '22 21:09

Slappy


Returning any non-object from the constructor is practically the same as exiting the constructor. (The constructor will return a new object, with a prototype if one was specified.)

So, returning null, undefined, or 42 from the constructor are equivalent.

Check out section 13.2.2 of the ECMAScript spec (pdf) for more info.

like image 31
Emmett Avatar answered Sep 23 '22 21:09

Emmett