javascript - 有人可以解释一下这个看似奇怪的分配 `{key=value} = argument`

标签 javascript class subclass

上下文:这是 javascript tutorial 中的一项任务。该代码应该生成一个子类 ExtendedClockClock允许控制台以自定义的时间间隔显示当前时间。

Class Clock {
  constructor({ template }) {
    this._template = template;
  }

  _render() {
    let date = new Date();

    let hours = date.getHours();
    if (hours < 10) hours = '0' + hours;

    let mins = date.getMinutes();
    if (mins < 10) min = '0' + mins;

    let secs = date.getSeconds();
    if (secs < 10) secs = '0' + secs;

    let output = this._template
      .replace('h', hours)
      .replace('m', mins)
      .replace('s', secs);

    console.log(output);
  }

  stop() {
    clearInterval(this._timer);
  }

  start() {
    this._render();
    this._timer = setInterval(() => this._render(), 1000);
  }
}

这是教程中给出的解决方案中奇怪的一行:

class ExtendedClock extends Clock {
  constructor(options) {
    super(options);
    let { precision=1000 } = options;  // what is this?
    this._precision = precision;
  }

  start() {
    this._render();
    this._timer = setInterval(() => this._render(), this._precision);

} }; 另一个问题:我的代码如下。为什么这不起作用?

class ExtendedClock extends Clock {
  constructor({template, precision = 1000}) {
    super({template})
    this._precision = precision
  }

  start() {
    super.start()
    this._timer = setInterval(() => this._render(), this._precision)
  }
}

最佳答案

这是带有默认值的对象解构语法。如果您要解构的对象包含 precision 键,则将使用该值,但如果不包含,则将使用 1000

如果键存在,则将使用其值:

const options = { precision: 800 };
const { precision = 1000 } = options;
console.log(precision); // logs 800

但如果键不存在,将使用默认值:

const options = {};
const { precision = 1000 } = options;
console.log(precision); // logs 1000
<小时/>

您的代码可能不起作用,因为当您调用 super.start() 时,父类(super class)会使用

启动循环
setInterval(() => this._render(), 1000);

您的代码在调用此函数后启动一个循环,但两个循环现在都在运行,导致父类(super class)的 setInterval 每 1000 毫秒调用一次渲染函数,然后每个 精度分别调用一次子类循环的毫秒数。

不要在循环开始时调用 super.start(),而是尝试仅调用 this._render()

关于javascript - 有人可以解释一下这个看似奇怪的分配 `{key=value} = argument`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52801891/

相关文章:

iphone - 从自定义 UIControl 子类转发事件

javascript - 仅当主体具有 X 类时才运行代码?

使用 List 类和 Pair 类的 C++ undefined reference 错误

python - JSON 到 Python 对象

php - 从 UML 类图生成 PHP 类的软件

Scala:是否可以定义一个扩展其类参数的类?

javascript - 如何使用 javascript 单击图像的特定坐标

javascript - jQuery:仅返回文本的一部分

javascript - 使用屏幕宽度和高度动态更改 Javascript 以提高响应能力

python - 子类化 python 的字典,重写 __setitem__ 不保留新值