Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript constructor with optional parameters

I am learning Javascript now and coming from the background of Java. In Java we have overloaded constructors wherein, at compile time, the compiler will decide which version of constructor to be called.

In case of Javascript, we can have only one constructor. In this case, if the constructor has 3 arguments, how to pass only the third parameter.

Ex:

class Addition {
 constructor(a,b,c){
   console.log(a+B+c);
 }
}

Addition obj = new Addition(null, 40, null);
//or
Addition onj2 = new Addition(undefined, undefined, 45);

Is there a better way to do this in Javascript?

like image 356
zilcuanu Avatar asked Jun 06 '18 07:06

zilcuanu


People also ask

Can constructor have optional parameters?

The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.

How do you pass an optional parameter in a constructor?

You can use a question mark to define optional parameters in a class constructor function. Alternatively, you can set a default value for the parameter, which will be used if a value is not provided when instantiating the class.

Are JavaScript parameters optional?

Optional parameters are great for simplifying code, and hiding advanced but not-often-used functionality. If majority of the time you are calling a function using the same values for some parameters, you should try making those parameters optional to avoid repetition.

Can default constructor have parameters?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .


1 Answers

You may use EcmaScript's parameter destructuring with default values to achieve that. Additionally, you need to use const (or let, or var) keyword to create variables.

class Addition {
  constructor({a = 0, b = 0, c = 0}) {
    console.log(a + b + c);
  }
}

const obj = new Addition({a: null, b: 40, c: null});
const onj2 = new Addition({c: 45});
like image 143
31piy Avatar answered Sep 23 '22 15:09

31piy