Javascript 属性未定义
我正在制作一个时钟类,它将每秒生成时间Javascript 属性未定义,javascript,Javascript,我正在制作一个时钟类,它将每秒生成时间 class Clock { constructor(template) { this._template = template; this._timer = null; } render() { var date = new Date(); var output = this._template .replace("h", date.getHours()) .rep
class Clock {
constructor(template) {
this._template = template;
this._timer = null;
}
render() {
var date = new Date();
var output = this._template
.replace("h", date.getHours())
.replace("m", date.getMinutes())
.replace("s", date.getSeconds());
console.log(output);
}
start() {
this.render();
this._timer = setInterval(this.render, 1000);
}
}
var clock = new Clock("h:m:s");
clock.start();
起初,这是正常的。输出与我期望的相同。然后,将出现一个错误
TypeError:无法读取未定义的属性“replace”
。这很奇怪。为什么我的模板
属性变得未定义?您正在将此属性传递给设置超时
函数,因此此
上下文被更改。您需要.bind(this)
,一切都将按预期工作
类时钟{
构造函数(模板){
这个。_template=模板;
这是。_time=null;
}
render(){
变量日期=新日期();
var输出=此模板
.replace(“h”,date.getHours())
.replace(“m”,date.getMinutes())
.replace(“s”,date.getSeconds());
控制台日志(输出);
}
开始(){
这个。render();
this._timer=setInterval(this.render.bind(this),1000);//由于this.render
不是箭头函数,当通过setInterval
使用时,它将丢失其this
绑定
或者
- 使其成为箭头函数(
render=()=>{…}
),或
- 在
setInterval
调用中绑定它:
this._timer = setInterval(this.render.bind(this), 1000);
时钟构造函数在哪里调用?听起来好像模板
最初已经未定义(或者很可能在调用渲染之前变得未定义)。@briosheje抱歉,我已经编辑了它。或者使用箭头函数:)@NikitaMadeev是的,也可以;)