我需要比较一个名为'让时间'的变量。比较需要在名为“ utcChange ”的单独功能中执行(单击按钮后)。我想,如果我在开始时声明这个变量,那么它就可以在任何地方访问。为什么 utcChange 函数中的语句不起作用?
let hours;
class Clock {
el: Element;
constructor(element) {
this.el = element;
setInterval(() => this.run(), 1000)
}
run() {
var time = new Date();
let hours = time.getHours()+utcValue;
var hoursChanged = hours.toString();
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
if (hoursChanged.length < 2) {
hoursChanged = '0' + hoursChanged;
}
if (minutes.length < 2) {
minutes = '0' + minutes;
}
if (seconds.length < 2) {
seconds = '0' + seconds;
}
var clockStr = hours + ' : ' + minutes + ' : ' + seconds;
this.el.textContent = clockStr;
}
}
var clock = new Clock(document.getElementById('tsClock'));
var utcButton = document.getElementById('button');
utcButton.addEventListener("click", utcChange);
var utcValue = 0
function utcChange(){
if (hours < 23) {
utcValue += 1
}
}
答案 0 :(得分:3)
类的let
函数中的局部变量会影响外部变量。从声明中删除run() {
var time = new Date();
hours = time.getHours()+utcValue;
var hoursChanged = hours.toString(); // Use without `let`
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString()
...
}
部分。
glboal
最好不要使用hours
变量。将变量设为字段,并使用对象的该字段访问A
。
答案 1 :(得分:1)
let hours
表示只能从其定义的函数中访问该变量。
要从其他功能使用它,请将其设为字段。
例如:
class Clock {
hours: number;
run() {
this.hours = ...;
}
}
function utcChange() {
if (clock.hours < 23)
// ...
}