前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >按照调用实例,实现下面的Person方法

按照调用实例,实现下面的Person方法

原创
作者头像
剁椒鱼鳞
发布2023-05-30 10:18:34
1890
发布2023-05-30 10:18:34
举报
文章被收录于专栏:前端小学生前端小学生

要求如下:

代码语言:javascript
复制
Person("Li");
// 输出: Hi! This is Li!

Person("Dan").sleep(10).eat("dinner");
// 输出:
// Hi! This is Dan!
// 等待10秒..
// Wake up after 10
// Eat dinner~

Person("Jerry").eat("dinner").eat("supper");
// 输出:
// Hi This is Jerry!
// Eat dinner~
// Eat supper~

Person("Smith").sleepFirst(5).eat("supper");
// 输出:
// 等待5秒
// Wake up after 5
// Hi This is Smith!
// Eat supper

代码如下:

代码语言:javascript
复制
function Person2(name){
    this.isRunFlag = false;
    this.name = name;
    this.taskArr = [];
    function task (name) {
        console.log(`Hi! This is ${name}!`);
    }
    this.taskArr.push(task.bind(this, name));
    this.run();
}
Person2.prototype.eat = function (food) {
    const task = food => {
        console.log(`Eat ${food}~`);
    }
    this.taskArr.push(task.bind(this, food));
    this.run();
    return this;
}
Person2.prototype.sleep = function (time) {
    const task = new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(`Wake up after ${time}`);
            resolve();
        }, time * 1000);
    })
    this.taskArr.push(task);
    this.run();
    return this;
}
Person2.prototype.sleepFirst = function (time) {
    const task = new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(`Wake up after ${time}`);
            resolve();
        }, time * 1000);
    })
    this.taskArr.unshift(task);
    this.run();
    return this;
}
Person2.prototype.run = function () {
    if (this.isRunFlag) {
        return;
    }else{
        this.isRunFlag = true;
        const gogogo = () => {
            if (this.taskArr.length) {
                let task = this.taskArr.shift();
                if (task.then) {
                    task.then(() => {
                        gogogo();
                    })
                } else {
                    task();
                    gogogo();
                }
            } else {
                this.isRunFlag = false;
            }
        }
        Promise.resolve().then((res) => {
            gogogo();
        }).catch((error) => {
            console.log("error:", error);
        })
    }
}
function Person(name){
    return new Person2(name);
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档