Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
194
rated 0 times [  200] [ 6]  / answers: 1 / hits: 17439  / 13 Years ago, fri, december 23, 2011, 12:00:00

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 );

More From » javascript

 Answers
16

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();
}
}

[#88401] Thursday, December 22, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lizet

Total Points: 479
Total Questions: 96
Total Answers: 113

Location: Mexico
Member since Sun, Jul 25, 2021
3 Years ago
;