小编oen*_*lli的帖子

如果JavaScript构造函数失败,它应该返回什么?

如果我有一个无法实例化的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)

但似乎应该有更好的方法.

javascript constructor class

38
推荐指数
4
解决办法
1万
查看次数

标签 统计

class ×1

constructor ×1

javascript ×1