如何在Javascript中使用new调用的构造函数返回null? [英] How to return null from a constructor called with new in Javascript?

查看:71
本文介绍了如何在Javascript中使用new调用的构造函数返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使构造函数在某些内容失败时中止对象构造,例如它无法获取画布。

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.

但是当我使用 new 时,我看到klass()总是返回这个无论是否返回null或任何其他值,我都可以解决此问题以返回null吗?

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?

现在我想到了,解决方案可能要在klass()中创建新实例并返回该实例或null,而不是使用 new ,是否有更好的解决方案?

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


推荐答案

你可以制作工厂功能或静态工厂方法代替:

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

这篇关于如何在Javascript中使用new调用的构造函数返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆