JS OOP 简单示例

103 阅读1分钟
function stopWatch() {
  let startTime = null
  let endTime = null
  let running = false
  let duration = 0
  this.start = function () {
    if (running) {
      throw new Error('stoWatch is running!')
    }
    startTime = new Date()
    running = true
  }
  this.stop = function () {
    if (!running) {
      throw new Error('stopWatch is started!')
    }
    running = false
    endTime = new Date()
    const seconds = (endTime.getTime() - startTime.getTime()) / 1000
    duration += seconds
  }
  this.reset = function () {
    running = false
    startTime = null
    endTime = null
    duration = 0
  }
  Object.defineProperty(this, 'duration', {
    get: function() {
      return duration
    }
  })
}