简体   繁体   中英

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?

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}); 

I hope this solved you question :D

 class Addition { constructor(a=null,b=null,c=null){ console.log(a+b+c); } } var obj = new Addition(null, 40, null); var onj2 = new Addition(undefined, undefined, 45); 

There is no possibility of overloading in JS, but you can work with Object destructuring . They can even be complex and refer to other default parameters, like:

 function rangeMessage({from=1, to=from+1, message=(counter) => `Hello ${counter}`}={}) { for(from; from <= to; from++) { console.log(message(from)); } } rangeMessage({from: 10, to: 20}); rangeMessage({to: 10, message:(counter) => `Bye ${counter}`}) rangeMessage() function sumABC({a=null, b=null, c=null}={}) { let result = 0; if(a) result += a; if(b) result += b; if(c) result += c; return result; } console.log(sumABC()); console.log(sumABC({a:10})); console.log(sumABC({b:5})); console.log(sumABC({b: 10, c: 5})); 

The {} = {} part does the same as the other destructuring assignments - if no object was passed in, assume an empty object (which is then filled by the object destructuring statements from the left side).

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