I'm trying to implement a sort of Constructor Pattern into a library for a project. But, I want to check for certain conditions being passed before returning an object. If those conditions aren't met, then I want to stop the constructor and return false.
But, I noticed that no matter what I set as the return value, an object is always returned!
Even if I do this:
new function () { return false; }
The result is still an Object object:
In Chrome:

In Firefox:

Is there any way to have a constructor fail in Javascript?
If those conditions aren't met, then I want to stop the constructor and return false.
You can't. The return value of a constructor function is ignored unless it's a non-null object. Any primitive value (or null) is just ignored by the new expression.
If you really want to have a flag value you return, you can do that, but it has to be an object. (But it's a bad idea, more below.) E.g.:
// The constructor
function Foo(num) {
if (num < 27) {
return Foo.BAD_ARG; // This is a bad idea, see the right way below
}
this.num = num;
}
Foo.BAD_ARG = {}; // Our special "bad argument" object
Is there any way to have a constructor fail in Javascript?
Yes: Throw an exception:
function Foo(num) {
if (num < 27) {
throw "`num` must be >= 27";
}
this.num = num;
}
Only way to return a non-object will be to wrap your constructor in a function and have it call (or not call) using new for you.
To do this, new on the outer function will need to be prohibited.
You can even use the same function, as long as you never call it with new.
function Foo() {
if (!(this instanceof Foo)) {
if (some_condition)
return false;
else
return new Foo()
}
// your constructor code here
}
var x = Foo();
The danger is if you forget and accidentally use new. To remedy this, you can use a separate function.
function Foo() {
// constructor code
}
function Bar() {
if (this instanceof Bar)
throw "Not a constructor"
if (some_condition)
return false;
else
return new Foo();
}
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