繁体   English   中英

JavaScript:如何在 Class 语法的构造函数中定义错误以拒绝创建实例?

[英]JavaScript: How to define an error in the constructor of Class syntax to deny creating an instance?

我在 JavaScript。 我希望我的 class Foo的构造函数在用户尝试创建Foo实例而不输入参数时抛出错误并拒绝创建实例。

class Foo{
  constructor(_x){

    /* I guess I need to define an error here
   
    */

    this.x = _x;
  }
}

const a = new Foo(810);// create instance
const b = new Foo(); // deny creating instance and throw the error message: "Please set an argument"

我试着写

if(!_x) return "Please set an argument";

在构造函数的头部,但它忽略了这一行并意外创建了一个属性x未定义的实例。

如何定义错误以拒绝创建实例?

你可以简单地throw一个错误

if(!_x) {
    throw new Error("No argument was passed to the constructor");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM