Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Es6 class constructor check if arguments is passed

Let's say I have a class with a parameter for its constructor. Can I make sure that a parameter is passed in when instantiating the class?

class Test {
    constructor(id) {}
} 

// would throw some kind of error

var test = new Test();

// ok

var test = new Test(1);
like image 974
Lun Zhang Avatar asked Feb 12 '26 06:02

Lun Zhang


1 Answers

Check in the constructor if the argument is not defined (=== undefined), and if it is throw an error:

class Test {
    constructor(id) {
      if(id === undefined) {
        throw new Error('id is undefined');
      }
    }
} 

new Test();
like image 189
Ori Drori Avatar answered Feb 13 '26 18:02

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!