有人可以解释这个看似奇怪的赋值`{key=value} = argument` [英] can someone explain this seemingly weird assignment `{key=value} = argument`
问题描述
上下文:这是javascript教程中的一项任务.该代码应该生成 Clock
的子类 ExtendedClock
,允许控制台以自定义的时间间隔显示当前时间.
Context: this is a task in a javascript tutorial. The code is supposed to generate a subclass ExtendedClock
of Clock
that allows the console to show the current time in a customized interval of time.
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);
}
}
这是教程中给出的解决方案中奇怪的一行:
Here comes the weird line in solution given in the tutorial:
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);
}};另一个问题:我的代码如下.为什么这不起作用?
} }; Another problem: My code is the following one. Why doesn't this work?
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
.
That's object destructuring syntax with a default value. If the object you're destructuring contains a precision
key, that value will be used, but if it does not, 1000
will be used.
如果键存在,将使用它的值:
If the key exists, its value will be used:
const options = { precision: 800 };
const { precision = 1000 } = options;
console.log(precision); // logs 800
但如果键不存在,将使用默认值:
but if the key does not exist, the default value will be used:
const options = {};
const { precision = 1000 } = options;
console.log(precision); // logs 1000
<小时>
您的代码可能不起作用,因为当您调用 super.start()
时,超类以
setInterval(() => this._render(), 1000);
您的代码在调用后开始一个循环,但现在两个循环都在运行,导致超类的 setInterval
每 1000 毫秒调用一次渲染函数,然后每个 precision 也分别调用一次
ms 由您的子类循环.
Your code starts a loop after this is called, but both loops are now running, causing the render function to be called every 1000ms by the superclass's setInterval
, and then also separately every precision
ms by your subclass's loop.
不要在循环开始时调用 super.start()
,而是尝试只调用 this._render()
.
Instead of calling super.start()
at the beginning of your loop, try just calling this._render()
.
这篇关于有人可以解释这个看似奇怪的赋值`{key=value} = argument`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!