簡體   English   中英

具有可選參數的javascript構造函數

[英]javascript constructor with optional parameters

我現在正在學習Javascript,並且來自Java背景。 在Java中,我們有重載的構造函數,在編譯時,編譯器將決定要調用哪個版本的構造函數。

如果使用Javascript,則只能有一個構造函數。 在這種情況下,如果構造函數具有3個參數,則如何僅傳遞第三個參數。

例如:

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

有沒有更好的方法來用Javascript做到這一點?

您可以使用EcmaScript的參數解構和默認值來實現。 此外,您需要使用const (或letvar )關鍵字來創建變量。

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

我希望這可以解決您的問題: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); 

JS中沒有重載的可能性,但是您可以使用Object destructuring 它們甚至可能很復雜,並引用其他默認參數,例如:

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

{} = {}部分的作用與其他銷毀結構的分配相同-如果未傳入任何對象,則假定為空對象(然后由左側的對象銷毀語句填充該對象)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM