This question already has an answer here:
ES6 Object Destructuring Default Parameters
                                
                                    (1个答案)
                                
                        
                2年前关闭。
            
        

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

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()时,超类会使用

setInterval(() => this._render(), 1000);


您的代码在调用此函数后会启动一个循环,但现在两个循环都在运行,导致渲染函数由超类的setInterval每隔1000ms调用一次,然后又由子类的循环每隔precision ms调用一次。

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

关于javascript - 有人可以解释这个看似奇怪的任务吗?{key = value} = arguments` [duplicate],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52801891/

10-09 21:59