javascript - 属性变得未定义
问题描述
我正在制作一个时钟类,它会每秒生成时间。
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: Cannot read property 'replace' of undefined
。真奇怪。为什么我的template
属性变得未定义?
解决方案
您正在传递this.render
给该setTimeout
函数,因此this
上下文已更改。你需要.bind(this)
,一切都会按预期工作。
class Clock {
constructor(template) {
this._template = template;
this._time = 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.bind(this), 1000); // <-- here
}
}
new Clock('h:m:s').start();
推荐阅读
- bash - 从脚本运行时bash脚本颜色不起作用
- apache-flink - Flink SQL 横向表语法是什么意思
- c - compare_exchange_strong/weak 可能会看到较旧的值吗?
- algorithm - 这意味着我们可以在多项式时间内验证背包问题的解决方案?
- javascript - AngularJS中ngRepeat中的ngRepeat问题
- python - python 3.8 tkinter从方法调用新窗口创建一个空白窗口
- windows - powershell 从对象数组中获取名称
- java - 使用“IN”子句的内容解析器动态查询
- jena - Jena 查询执行时间
- cuda - 为什么我会收到关于 cudaMemcpyToArray(...) 被弃用的警告?