javascript - 我真的应该拥有所有这些“这个”吗?在我的班级内所有变量?
问题描述
我正在用 JavaScript 练习 OOP,所以我编写了这个看起来可以正常工作的自定义 Stopwatch 类。我可以创建新的秒表(例如 let sw = new Stopwatch();),然后创建 sw.start() 和 sw.stop() 它。在使用 sw.duration() 检查调用前后的时间。
(1) 但是,我最终this.
在每个变量的前面添加了,这很丑陋而且看起来是多余的——但我无法让它正常工作。所以我想知道我是否做错了 - 还是这是最好的方法?
(2) 我也没有构造函数()。我应该有一个吗?
(3) 是否建议以某种方式将我的 duration() 从函数更改为属性,或者将其重命名为 getDuration?这里的最佳做法是什么?
class Stopwatch {
start() {
if (this.isRunning) throw new Error("Already running!");
this.isRunning = true;
this.startTime = new Date();
console.log("Started...");
}
stop() {
if (!this.isRunning) throw new Error("Not running!");
this.isRunning = false;
this.stopTime = new Date();
console.log(`Stopped after ${this.duration()} seconds.`);
}
duration() {
if (!this.startTime) throw new Error("Not yet started.");
if (!this.isRunning) {
// Stopwatch has been stopped
this.timeDiff = (this.stopTime - this.startTime) / 1000;
} else {
// Stopwatch is still running
this.timeDiff = (new Date() - this.startTime) / 1000;
}
return this.timeDiff;
}
}
// Let's test a Stopwatch...
let sw = new Stopwatch();
// sw.start();
// sw.duration();
// sw.stop();
更新:感谢所有伟大的回复/评论!作为参考,这里是我更新的代码,并实施了建议。
class Stopwatch {
constructor() {
this.isRunning = false;
this.startTime = null;
this.stopTime = null;
}
start() {
if (this.isRunning) throw new Error("Already running!");
this.isRunning = true;
this.startTime = new Date();
console.log("Started...");
}
stop() {
if (!this.isRunning) throw new Error("Not running!");
this.isRunning = false;
this.stopTime = new Date();
console.log(`Stopped after ${this.duration} seconds.`);
}
get duration() {
if (!this.startTime) throw new Error("Not yet started.");
let timeDiff = null;
if (!this.isRunning) {
// Stopwatch has been stopped
timeDiff = (this.stopTime - this.startTime) / 1000;
} else {
// Stopwatch is still running
timeDiff = (new Date() - this.startTime) / 1000;
}
return timeDiff;
}
}
// Let's test a Stopwatch...
let sw = new Stopwatch();
// sw.start();
// sw.duration();
// sw.stop();
解决方案
推荐阅读
- c# - dll 和 pdb 已加载,但“没有为此文档加载任何符号
- r - R中的种子限制
- java - 为什么在春季尝试注入具有“请求”范围的bean时,带有名称的bean会抛出错误但没有名称的bean不会?
- django - 时区日期到python日期
- java - 如果其中的标签不存在,如何在Java中使用replaceAll替换一段代码?
- reactjs - 创建反应应用程序:npm 错误!在“....”附近解析时 JSON 输入意外结束
- python - 包含整数和字符串值的两个列表之间的区别?
- r - 带有自定义分组的箱线图 (ggplot2)
- azure - 在 docker、Github 操作或 Azure 容器注册表中忽略了“公共”文件夹
- json - 使用 React-Native 从嵌套 JSON 中获取数据