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?
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.
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.
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.
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() .
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With