I'm trying to get my head around OOP in Javascript (I've never really used OOP in any other language either, so this is my first experience of it). I've written a class that requires an input for the constructor, but the constructor only only works with a specifically formatted string.
I have a regex that I can use to check the input against, but I don't know what I am supposed to do if it doesn't match (or if there is no input at all). Should I throw an exception of some sort? If so, how do I go about that?
JavaScript constructors (functions called with the new
keyword) always need to return an object, you can't return false
, null
or similiar like when invoked normal. So, you have two options:
throw
statement. Then, catch them outside the construction with a try
statementinvalid
pointer. The Date
constructor does that for instance, getting attributes then results in NaN
s.Additionally (especially when using exceptions) you might provide an extra validation function (which returns boolean) as a static property on the constructor, so you can use that even before constructing an object. Example:
function Decryption(str) {
if (! Decryption.test(str))
throw new SyntaxError("invalid encryption");
this.result = decrypt(str);
}
Decryption.test = function(str) {
return /MyCoolRegExp/.test(str);
};