我试图让构造函数在某些东西失败时中止对象构造,例如它无法获得画布.
但是当我使用时,new我看到klass()始终返回,this无论返回null或任何其他值,我可以解决此问题以返回null吗?
现在我想到,一个解决方案可能是在klass()中创建新实例并返回该实例或null,而不是使用new,是否有更好的解决方案?
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 );
Run Code Online (Sandbox Code Playgroud)
Lin*_*een 12
更好的解决方案是抛出一个错误:
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
}
Run Code Online (Sandbox Code Playgroud)
编辑:构造函数可以"强制"不返回实例:
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? ;-)
Run Code Online (Sandbox Code Playgroud)
奇怪的是,但是,如果一个"构造"返回一个数字,字符串true,false等等,它实际上并返回一个实例.第二个解决方案仅在构造函数返回空数组[]或空对象时才有效{}.
Kos*_*Kos 12
您可以改为使用"工厂功能"或"静态工厂方法":
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();
Run Code Online (Sandbox Code Playgroud)
使用较新的类语法也是如此:
class Foo {
static CreateFoo() {
if (something) {
return null;
}
return new Foo();
}
}
Run Code Online (Sandbox Code Playgroud)