首页 > 解决方案 > 我真的应该拥有所有这些“这个”吗?在我的班级内所有变量?

问题描述

我正在用 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();

标签: javascriptclassoopthis

解决方案


推荐阅读