簡體   English   中英

如何使參數中的 javascript class 對象的屬性可選?

[英]How can I make javascript class object's attribute in the parameter optional?

我正在嘗試創建一個不需要任何參數但參數是可選的 class。 參數包含將被重組的單個 object。 如果他們只想覆蓋默認選項之一,我還希望用戶不必重新輸入整個選項列表。 這是我到目前為止達到的代碼:

class A {
  /**
   * @param {number} path The directory path to store at.
   * @param {boolean} timeStamp The value to check if timestamps are needed.
   */
  constructor({ path, timeStamp } = { path: "./", timeStamp: true }) {
    Object.defineProperty(this, "path", { writable: false, value: path });
    Object.defineProperty(this, "timeStamp", { writable: false, value: timeStamp });
  }
}

但這並沒有按預期工作。 我想到了這樣的事情:

const y = new A({ path: "./here", timeStamp: false });
console.log(y.path); // Logs "./here". As expected
console.log(y.timeStamp); // Logs  "false". As expected

const x = new A({ timeStamp: false });
console.log(x.path); // Logs "undefined". Should be the default value  "./"
console.log(x.timeStamp); // Logs "false". As expected

const z = new A();
console.log(z.path); // Logs "./". As expected
console.log(z.timeStamp); // Logs "true". As expected

提前致謝。

編輯:我不想使用很多參數,class 最終會有很多選項。 這是我要完成的工作: Electron's BrowserWindow documentations

如果沒有通過,您正在初始化整個 object,您實際上想要做的是使用默認值初始化解構屬性:

 constructor({ path = "./", timeStamp = true } = { })

使用兩個具有各自默認值的參數來設置構造函數:

constructor(path = "./", timeStamp = true)

這是我會怎么做

const defaultOptions =  { path: "./", timeStamp: true };
class A {
  /**
   * @param {number} path The directory path to store at.
   * @param {boolean} timeStamp The value to check if timestamps are needed.
   */
  constructor(options = { }) {
    const { path, timeStamp } = Object.assign({}, defaultOptions, options);
    Object.defineProperty(this, "path", { writable: false, value: path });
    Object.defineProperty(this, "timeStamp", { writable: false, value: timeStamp });
  }
}

您將 object 設置為默認值,並接收 object 作為初始化為空的參數。

使用 Object.assign 來“繼承”這些值。 第一個參數是一個空的 object,因為它是從其他對象接收屬性的目標。 在默認值之后設置傳遞的選項,以便它們覆蓋它們。

暫無
暫無

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

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