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.
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 .
A constructor doesn't return anything.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With