如果 JavaScript 构造函数失败,它应该返回什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5149619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What should a JavaScript constructor return if it fails?
提问by oenpelli
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.
如果我有一个无法实例化的 javascript 类,构造函数应该返回什么我可以测试。构造函数总是返回一个对象,所以如果构造函数失败,我不能返回 null。
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.
但似乎应该有更好的方法。
采纳答案by Slappy
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.
我的建议是努力打破并尽快打破。这将在测试期间非常明显地违反合同。
回答by Emmett
Returning any non-objectfrom the constructor is practically the same as exiting the constructor. (The constructor will return a new object, with a prototypeif one was specified.)
从构造函数返回任何非对象实际上与退出构造函数相同。(构造函数将返回一个新对象,prototype并指定了一个if 。)
So, returning null, undefined, or 42from the constructor are equivalent.
因此,从构造函数返回null、undefined或42是等效的。
Check out section 13.2.2 of the ECMAScript spec (pdf)for more info.
查看ECMAScript 规范 (pdf) 的第 13.2.2 节了解更多信息。
回答by Emmett
My first approach:
我的第一种方法:
- Don't allow a constructor to fail; consider alternatives
- 不允许构造函数失败;考虑替代方案
My second approach:
我的第二种方法:
- If a constructor fails, it must only fail because of a programming error and thus;
- should throw an exceptionand;
- must not return 'a status code'(see Emmett's answer for why returning
nulldoesn't work anyway)
- 如果构造函数失败,它只能因为编程错误而失败,因此;
- 应该抛出异常并且;
- 不得返回“状态代码”(请参阅 Emmett 的回答,了解为什么
null无论如何返回都不起作用)
I have never designed a constructor (something invoked as the target of new) to return anything except an object of the "expected" type.
我从来没有设计过一个构造函数(作为 的目标调用的东西new)来返回除了“预期”类型的对象之外的任何东西。
Fail fast, avoid being tooclever, and save time debugging hard-to-find bugs.
快速失败,避免太聪明,并节省调试难以发现的错误的时间。
Happy coding.
快乐编码。
回答by AFC
Use I sentinel. I like to
使用我哨兵。我喜欢
return {invalid:true};
This looks clean:
这看起来很干净:
var x = new X();
if (x.invalid) { // ...
(There's no way to return a non-true value from a constructor, so you can't put newin the conditional as you might with another language.)
(无法从构造函数返回非真值,因此您不能像使用另一种语言那样将new放入条件中。)

