繁体   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