实现一个英雄类Hero

2018-09-29  本文已影响0人  小小的白菜

原文

使用原生JS实现一个英雄类Hero, 可以按照以下方式调用(考察点: JavaScript流程控制)

class Hero {
    constructor(name) {
      this.name = name
      this.sum = 0
      this.promise = Promise.resolve()
    }

    sleep(time) {
      this.promise = this.promise.then(function () {
        console.log('在床上睡' + time + '毫秒...')
        return new Promise(function (resolve) {
          setTimeout(resolve, time)
        })
      })
      return this
    }

    kill(num) {
      const that = this
      this.promise = this.promise.then(function () {
        that.sum += num
        console.log(`${that.name} 已干掉 ${that.sum} 只怪兽!`)
        return Promise.resolve()
      })
      return this
    }
  }
  const hero = new Hero('超人');
  hero
    .kill(3)
    .sleep(100000)
    .kill(4)
上一篇下一篇

猜你喜欢

热点阅读