面试题:滴滴一道原型调用方面的题

掘金控制台给我的灵感

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>

    /*
     实现一个LazyMan,可以按照以下方式调用:
     1) LazyMan(“Hank”)输出:
     Hi! This is Hank!

     2) LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
     Hi! This is Hank!
     //等待10秒..
     Wake up after 10
     Eat dinner~

     3) LazyMan(“Hank”).eat(“dinner”).eat(“supper”)输出
     Hi This is Hank!
     Eat dinner~
     Eat supper~

     4) LazyMan(“Hank”).sleepFirst(5).eat(“supper”)输出
     //等待5秒
     Wake up after 5
     Hi This is Hank!
     Eat supper
     */
    // 1. 同异步
    // 2. 原型


    function LazyMan(name){
        // 由于防止递归导致的死循环,在LazyMan新创建一个函数Man;
        function Man() {
            // 从第四个执行结果来看,Man一定是异步的;
            setTimeout(function () {
                console.log(` Hi! This is ${name}!`);
            },0)
        }
        Man.prototype.sleep = function (time) {
            /*setTimeout(function () {
                console.log(`Wake up after ${time}!`);
            },10000)*/ // 将此处异步的定时器变成同步;
            let curTime = new Date();
           setTimeout(function () {
               while(new Date()-curTime<time*1000){}
               console.log(`Wake up after ${time}!`);
           },0)
            return this;// 目的是实现链式调用;
        }
        Man.prototype.eat = function (food) {
            setTimeout(function () {
                console.log(`Eat ${food}~`);
            },0);
            //console.log(`Eat ${food}~`);
            return this;
        }
        Man.prototype.sleepFirst = function (time) {
            let  curTime = new Date();
            while(new Date()-curTime<time*1000){};
            console.log(`Wake up after ${time}!`)
            return this;
        }
        return new Man();
    }

    // LazyMan("Hank").sleep(10).eat("dinner");
    //LazyMan("Hank").eat("dinner").eat("supper");
    LazyMan("Hank").sleepFirst(5).eat("supper")
</script>
</body>
</html>
复制代码

转载于:https://juejin.im/post/5c871eedf265da2de165db35

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值