Javascript同Class实例间互相触发函数?番茄钟开发求助
解决番茄钟Timer实例互调与this绑定问题
嘿,我仔细看了你的番茄钟代码,发现两个关键问题导致你没法让两个Timer实例互相触发:一个是setInterval里的this绑定出错了,另一个是你的Timer类根本不知道另一个实例的存在,自然没法调用它的方法。下面一步步给你解决:
1. 修复setInterval的this绑定错误
你在intervalFunc里写的匿名函数,里面的this默认指向window(非严格模式下),根本不是Timer实例,所以this.countdown()根本执行不了。改成箭头函数就能解决,因为箭头函数会继承外层作用域的this:
intervalFunc() { // 一定要返回定时器ID,这样stopClock才能正常清除定时器 return setInterval(() => this.countdown(), 1000); }
同时,你的stopClock函数要正确使用这个返回的ID:
stopClock() { clearInterval(this.func); }
2. 让Timer实例知道它的"伙伴"是谁
要让session和btimer互相调用方法,得给每个Timer实例添加一个partner属性,用来存储对应的另一个实例。创建实例后互相赋值即可:
// 创建实例 session = new Timer(1, 60, s_off, s_timer, s_stop, s_increase, s_decrease); btimer = new Timer(5, 60, b_off, b_timer, b_stop, b_increase, b_decrease); // 互相设置伙伴关系 session.partner = btimer; btimer.partner = session;
然后在countdown函数里,当计时结束时,调用伙伴的time()方法(而不是自己的):
countdown() { // 检查是否到0 if (this.sec == 0) { this.min--; this.sec = 60; if (this.min < 0) { this.min = this.minsSet; this.sec = 0; this.off = true; this.stopClock(); // 先停止当前计时器 this.partner.time(); // 启动伙伴的计时器 return; // 提前退出,避免后续减秒操作 } } // 正常减秒并更新显示 this.sec--; let m = this.min.toString(); let s = this.sec < 10 ? `0${this.sec.toString()}` : this.sec.toString(); this.disp.html(m + ":" + s); }
3. 小优化:修复初始显示问题
你现在constructor里把sec设为60,第一次倒计时后会显示1:59,但用户预期初始应该是1:00。可以把初始sec改成0,再调整倒计时逻辑:
constructor(min, sec, off, disp, stopButton, increaseButton, decreaseButton) { this.min = min; this.minsSet = min; this.sec = sec || 0; // 初始秒数设为0 this.off = off; this.disp = disp; this.stopButton = stopButton; this.increaseButton = increaseButton; this.decreaseButton = decreaseButton; this.func; // 初始化显示 this.disp.html(`${this.min}:${this.sec < 10 ? '0' + this.sec : this.sec}`); }
把这些修改整合后,你的番茄钟就能实现工作计时结束自动触发休息计时,休息结束再触发工作计时的循环逻辑了。
内容的提问来源于stack exchange,提问作者Scott
相关产品推荐
相关产品推荐

