4 回答

TA貢獻1848條經驗 獲得超2個贊
您的代碼存在一些問題,但請嘗試以下操作:
class Clock {
constructor(template) {
this.template = template;
this.date = new Date(); // call date
}
render() {
let hours = this.date.getHours(); // get hours
if (hours < 10) hours = "0" + hours;
let minutes = this.date.getMinutes(); // get minutes
if (minutes < 10) minutes = "0" + minutes;
let seconds = this.date.getSeconds(); // get seconds
if (seconds < 10) seconds = "0" + seconds;
let output = hours + ":" + minutes + ":" + seconds;
return output; // output
}
stop() {
// stop interval
clearInterval(this.timer);
}
start() {
// start interval
this.timer = setInterval(() => this.render(), 1000);
}
}
const clock = new Clock("");
clock.start();
您的構造函數設置不正確(但也未使用)并且您的this引用已關閉。
實時示例: https ://codesandbox.io/s/clock-test-1r8dm?file=/src/index.js
根據 OP 的評論,OP 可能要求增加時間。如果是這樣,請將渲染替換為
render() {
const nD = new Date();
let hours = nD.getHours(); // get hours
if (hours < 10) hours = "0" + hours;
let minutes = nD.getMinutes(); // get minutes
if (minutes < 10) minutes = "0" + minutes;
let seconds = nD.getSeconds(); // get seconds
if (seconds < 10) seconds = "0" + seconds;
let output = hours + ":" + minutes + ":" + seconds;
return output; // output
}

TA貢獻1824條經驗 獲得超5個贊
setInterval 接受函數的名稱
class Clock {
constructor(template) {
this.template = template;
this.timer = this.timer;
this.date = new Date();
}
render = () => {
let time = this.date;
let hours = time.getHours();
if (hours < 10) hours = "0" + hours;
let minutes = time.getMinutes();
if (minutes < 10) minutes = "0" + minutes;
let seconds = time.getSeconds();
if (seconds < 10) seconds = "0" + seconds;
let output = hours + ":" + minutes + ":" + seconds;
console.log(output);
}
stop = () => {
clearInterval(this.timer);
}
start =() => {
this.timer = setInterval(this.render, 1000);
}
}
var clock = new Clock({ template: "" });
clock.start();

TA貢獻1815條經驗 獲得超10個贊
setInterval需要一個回調函數。你不應該執行它。
start =() => {
this.timer = setInterval(() => this.render(), 1000);
}
class Clock {
constructor(template) {
this.template = template;
this.timer = this.timer;
// this.date = new Date(); // call date
}
render = () => {
const date = new Date();
let hours = date.getHours(); // get hours
if (hours < 10) hours = '0' + hours;
let minutes = date.getMinutes(); // get minutes
if (minutes < 10) minutes = '0' + minutes;
let seconds = date.getSeconds(); // get seconds
if (seconds < 10) seconds = '0' + seconds;
let output = hours + ':' + minutes + ':' + seconds;
console.log(output)
return output; // output
}
stop = () => { // stop interval
clearInterval(this.timer);
}
start = () => { // start interval
this.timer = setInterval(this.render, 1000);
}
}
var clock = new Clock({ template: '' });
clock.start();

TA貢獻1770條經驗 獲得超3個贊
setInterval 創建了一個新范圍,所以this
在 setInterval 內部不是同一個類實例,所以this.date.getHours()
會拋出錯誤,因為this.date
will undefined
。
添加回答
舉報