I'm trying to make the constructor abort the object construction if something fails, for example it can't get a hold of a canvas.
But as I'm using new
I see that klass() always returns this
regardless of any return null or any other value, can I work around this to return null?
Now that I think of, a solution may be to create the new instance inside klass() and return that instance or null, and not use new
, is there a better solution?
function klass( canvas_id ) {
var canvas = document.getElementById( canvas_id );
if( ! ( canvas && canvas.getContext ) ) {
return null;
}
}
var instance = new klass( 'wrong_id' );
console.log( instance, typeof instance );
We can not return any value from constructor... A constructor does not return anything; the "new" operator returns an object that has been initialized using a constructor. If you really want a constructor that may return null, perhaps you should check out the factory method pattern.
If somewhere in the "more code" (line 8 in your example), dataList is set to null, then the getData() method will return null. But the new operator itself never returns null, so there's no need to check for that.
JavaScript uses the null value to represent the intentional absence of any object value. If you find a variable or a function that returns null , it means that the expected object couldn't be created.
You could make a "factory function" or "static factory method" instead:
Foo.CreateFoo = function() {
// not to confuse with Foo.prototype. ...
if (something) {
return null;
}
return new Foo();
};
// then instead of new Foo():
var obj = Foo.CreateFoo();
Same thing using the newer class syntax:
class Foo {
static CreateFoo() {
if (something) {
return null;
}
return new Foo();
}
}
The better solution would be to throw an error:
function klass(canvas_id) {
var canvas = document.getElementById( canvas_id );
if( ! ( canvas && canvas.getContext ) ) {
throw new Error('Not a canvas');
}
}
// later...
try {
var c = new klass("canvas_id");
} catch(E) {
// error caught
}
EDIT: Constructors can be "forced" to not return an instance:
function Foo() {
var canvas = ...;
if ('undefined' == '' + Foo.CANVAS_CHECK)
Foo.CANVAS_CHECK = ( canvas && canvas.getContext );
if (!Foo.CANVAS_CHECK)
return []; // the constructor will actually return an empty array
// passed; initialize instance here
}
// later on...
var foo;
if (!((foo = new Foo()) instanceof Foo)) {
// Failed. Canvas is unsupported.
}
// You happy now, am not i am? ;-)
The odd thing is, however, that if a "constructor" returns a number, string, true
, false
, etc., it actually does return an instance. The second solution only works when the constructor returns an empty array []
or an empty object {}
.
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