JavaScript 流程控制

https://github.com/anotherso1a/37Hero/blob/master/chain.js

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

function HeroFather(name){
    this.name=name
    this.task=[]
    this.next=function(){
        var fn = this.task.shift()
        if(fn){
            fn()
        }
        return this
    }
    //关键步骤,将next方法执行回调
    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)

你可能感兴趣的:(JavaScript 流程控制)