使用原生JS
实现一个英雄类Hero
, 可以按照以下方式调用(考察点: JavaScript
流程控制)
-
Hero("37FEer")
输出:Hi!This is 37FEer!
-
Hero("37FEer").kill(1).recover(30)
输出:Hi!This is 37FEer!
-
Kill 1 bug
(注意:数量1
个,所以bug
是单数); Recover 30 bloods;
-
Hero("37FEer").sleep(10).kill(2)
输出:Hi!This is 37FEer!
- // 等待
10
秒.. -
Kill 2 bugs
(注意:数量2
个,所以bugs
是复数);
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)
网友评论