A 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'); } }
EDIT: Constructors may be "forced" not to return an instance:
function Foo() { var canvas = ...; if ('undefined' == '' + Foo.CANVAS_CHECK) Foo.CANVAS_CHECK = ( canvas && canvas.getContext ); if (!Foo.CANVAS_CHECK) return [];
However, it is strange that if the "constructor" returns a number, a string, true , false , etc., it actually returns an instance. The second solution only works when the constructor returns an empty array [] or an empty object {} .
Linus kleen
source share