上下文:这是 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()
时,父类(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/