如果JavaScript构造函数失败,它应该返回什么? [英] What should a JavaScript constructor return if it fails?

查看:116
本文介绍了如果JavaScript构造函数失败,它应该返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个javascript类,不能实例化什么应该构造函数返回,我可以测试。构造函数总是返回一个对象,所以如果构造函数失败,我不能返回null。

If I have a javascript class which cannot be instantiated what should the constructor return that I can test for. The constructor always returns an object so I cannot return null if the constructor fails.

function SomeClass(id) {
  if(typeof(id) === 'number' {
    // This is good
    this.id = id;
  } else {
    // This is bad
    // This return is ignored and an empty object is returned
    return null;
  }
}

var a = new SomeClass('badParam');
if(a){
  // is true even though the class expects a number.
}

// Could use this check
if(a.id !== undefined){
  // Do some stuff
}

但是它似乎应该有一个更好的方法。

but it seems there should be a better way.

推荐答案

这可能是最好抛出异常通知调用者初始化失败,并采取适当的措施。

It is probably best to throw an exception to notify the caller that the initialization failed and to take appropriate action.

返回代码很好,但是大多数情况下,调用者没有动机去实现对返回代码的检查。

Return codes are fine, but for the most part there is no motivation for the caller to implement the checks on the return code.

我的建议是努力工作,尽快休息。这将使合同违规在测试期间非常明显。

My advice is to break hard and break soon. This will make contract violations very evident during testing.

这篇关于如果JavaScript构造函数失败,它应该返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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