【发布时间】:2011-07-06 04:44:25
【问题描述】:
如果我有一个无法实例化的 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
}
但似乎应该有更好的方法。
【问题讨论】:
-
我会返回 undefined
标签: javascript class constructor