https://github.com/anotherso1a/37Hero/blob/master/chain.js
使用原生JS實(shí)現(xiàn)一個(gè)英雄類Hero, 可以按照以下方式調(diào)用(考察點(diǎn): JavaScript流程控制)
(1) Hero("37FEer")輸出:
Hi!This is 37FEer!
(2) Hero("37FEer").kill(1).recover(30)輸出:
Hi!This is 37FEer!
Kill 1 bug (注意:數(shù)量1個(gè)仍秤,所以bug是單數(shù))世曾;
Recover 30 bloods;
(3) Hero("37FEer").sleep(10).kill(2)輸出:
Hi!This is 37FEer!
// 等待10秒..
Kill 2 bugs (注意:數(shù)量2個(gè),所以bugs是復(fù)數(shù))迫横;
function HeroFather(name){
this.name=name
this.task=[]
this.next=function(){
var fn = this.task.shift()
if(fn){
fn()
}
return this
}
//關(guān)鍵步驟,將next方法執(zhí)行回調(diào)
var that=this
setTimeout(function(){
console.log(`Hi, my name is ${that.name}`)
that.next()
})
}
HeroFather.prototype.sleep=function(a){
var that=this
var fn = function(){
var s = a
console.log(`I need sleep ${s}s`)
setTimeout(function(){
that.next()
},s*1000)
}
this.task.push(fn)
return this
}
HeroFather.prototype.kill=function(a){
var that = this
var fn = function(){
var s = a
console.log(`I killed ${s} bug${s>1?'s':''}`);
that.next()
}
this.task.push(fn)
return this
}
HeroFather.prototype.recover=function(a){
var that = this
var fn = function(){
var s = a
console.log(`I recovered ${s} HP`);
that.next()
}
this.task.push(fn)
return this
}
function Hero(name){
return new HeroFather(name)
}
Hero('37FEer')
Hero('37FEer').kill(2).recover(30)
Hero('37FEer').sleep(1).kill(2)