我用 es6 创建了一个类,需要在 options
参数中定义一个属性。
class MyClass{
constructor(options){
if(typeof options.name === "undefined")
console.error("MyClass.constructor: options.name is not defined");
return this;
}
}
我可以记录错误,但我不希望此类的用户继续。我要返回什么?我还应该返回该类的实例吗?
最佳答案
在这种情况下我会抛出一个错误。我会做这样的事情:
class MyClass{
constructor(options){
if(typeof options.name === "undefined")
throw new Error("MyClass.constructor: options.name is not defined");
return this;
}
}
关于javascript - 当一个重要的构造函数参数被遗漏时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37230334/