如果我有一个无法实例化的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
}
Run Code Online (Sandbox Code Playgroud)
但似乎应该有更好的方法.