JavaScript 流程控制

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)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容