问题
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)
}
}
回答1:
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
Your code probably doesn't work because when you call super.start(), the superclass starts a loop with
setInterval(() => this._render(), 1000);
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 precisionms by your subclass's loop.
Instead of calling super.start() at the beginning of your loop, try just calling this._render().
回答2:
this weird code is just a handy way to overwrite the default value if there is a Property for it.
let options = { precision: 999, template: 'h:m:s' };
let { precision = 1000 } = options; // precision === 999
let options = { template: 'h:m:s' };
let { precision = 1000 } = options; // precision === 1000
For the second issue I would need some more input. Which error do you get?
来源:https://stackoverflow.com/questions/52801891/can-someone-explain-this-seemingly-weird-assignment-key-value-argument