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

2023-05-30 10:18:34 浏览数 (2)

要求如下:

代码语言: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);
}

0 人点赞