我正在做一个HTML的customelement,但是当我在浏览器中运行它时,我得到一个非常有趣的错误。这是我的代码。
class clock extends HTMLElement {
constructor() {
super()
this.time = new Date(this.getAttribute('time'));
this.span = document.createElement('span')
this.appendChild(this.span)
}
Timer() {
let Now = this.time;
let Seconds = Now.getSeconds();
let Minutes = Now.getMinutes();
let Hours = Now.getHours();
Minutes = Minutes < 10 ? "0" + Minutes : Minutes;
document.getElementById("digitalClock").textContent = Hours + ":" + Minutes;
}
connectedCallback(){
this.span.innerHTML = `...<span id="digitalClock"></span>`;
this.Timer();
this.myClockTimer = setInterval(this.Timer, 5000);
}
disconnectedCallback(){
clearInterval(this.myClockTimer);
}
}
customElements.define('worktime-clock', clock)
当我运行这段代码时,当我在connectCallback函数中使用this.Timer()调用时,Timer函数运行得很好,但是一行之后,当它进入一个循环时,它说Now在Timer函数中未定义。看来是关于在setinterval中调用的问题,但是,函数肯定是按照预期的那样反复运行。谁知道问题出在哪里?
你失去了正确的 this
上下文,将Timer函数作为回调传递。结果是 this
(在回调中)现在指向 window
代替。您可以使用 bind
来设置this-context。
this.myClockTimer = setInterval(this.Timer.bind(this), 5000);
这样做的目的是一样的
var that = this;
this.myClockTimer = setInterval(function() { that.Timer(); }, 5000);
另一个选择:
this.myClockTimer = setInterval(function() { this.Timer(); }.bind(this), 5000);
或者一个箭头函数
<script>
customElements.define('worktime-clock', class extends HTMLElement {
updateTime() {
let Now = new Date();
const pad = x => String(x).padStart(2,'0');
const H = pad(Now.getHours());
const M = pad(Now.getMinutes());
const S = pad(Now.getSeconds());
this.innerHTML = `${H}:${M}:${S}`;
}
connectedCallback() {
this.myClockTimer = setInterval(() => {
this.updateTime();
}, 1e3);
}
disconnectedCallback() {
clearInterval(this.myClockTimer);
}
})
</script>
<worktime-clock>21:22:23</worktime-clock>
<script>
customElements.define('worktime-clock', class extends HTMLElement {
connectedCallback() {
this.myClockTimer = setInterval(() => {
this.innerHTML = new Date().toString().split` `[4];
}, 1e3);
}
disconnectedCallback() {
clearInterval(this.myClockTimer);
}
})
</script>
<worktime-clock>21:22:23</worktime-clock>