简体   繁体   中英

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

I'm in JavaScript. I want the constructor of my class Foo throw an error and deny creating an instance when an user tries to create instance of Foo without putting argument.

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"

I tried to write

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

at the head of constructor, but it ignored this line and unexpectedly created an instance whose property x is undefined.

How can I define error to turn down creating an instance?

You can simply throw an error :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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