构建类并且实现功能

问题: 要求设计 LazyMan 类,实现以下功能
LazyMan('Tony');
// Hi I am Tony

LazyMan('Tony').sleep(10).eat('lunch');
// Hi I am Tony
// 等待了10秒...
// I am eating lunch

LazyMan('Tony').eat('lunch').sleep(10).eat('dinner');
// Hi I am Tony
// I am eating lunch
// 等待了10秒...
// I am eating diner

LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
// Hi I am Tony
// 等待了5秒...
// I am eating lunch
// I am eating dinner
// 等待了10秒...
// I am eating junk food
  1. 首先需要了解constructor()函数
    1. 是一种用于创建和初始化 class 的特殊方法
    2. 在一个类中只能有一个 名为constructor的特殊函数,出现多个 constructor 函数会报一个 syntaxError 的错误。
    3. 在此构造函数中可以使用 super 关键字来调用一个父类的构造方法
    4. 如果没有显示指定构造方法,则会添加默认的 constructor 函数
  1. 了解什么是类。
    1. 类是用于创建对象的模板
    2. 类是特殊的函数,类语法有两个组成部分,一个是类表达式一个是类声明。
    3. 函数声明和类声明不同的地方在于,类声明不会提升,函数声明会提升。
  1. 静态方法
    4. 不能通过类实例调用,即不能通过 new LazyManClass().静态方法名调用。应该通过类本身调用。
    5. 静态方法通常是通用程序方法。比如汽车类中的通用名字’汽车’为一个静态属性,通用方法刹车为一个静态方法。
    6. 静态方法中调用同一个类中的静态方法,使用 this调用
    7. 非静态方法中调用类中的静态方法,需要通过类名或者构造函数的属性来调用

综上所述,实现代码如下:

class LazyManClass {  
    constructor(name) {  
        console.log(`I am ${name}`);  
        this.taskList = [];  
        setTimeout(() => {  
            this.next()  
        }, 0);  
    }  
    eat(string) {  
        var that = this;  
        var fn = function () {  
            console.log(`I am eating ${string}`)  
            that.next()  
        }  
        this.taskList.push(fn);  
        return this;  
    }  
    sleep(time) {  
        var that = this;  
        var fn = function () {  
            setTimeout(() => {  
                console.log(`等待了${time}秒...`)  
                that.next();  
            }, time * 1000)  
        }  
        this.taskList.push(fn)  
        return this;  
    }  
    sleepFirst(time) {  
        var that = this;  
        var fn = function () {  
            setTimeout(() => {  
                console.log(`等待了${time}秒...`)  
                that.next();  
            }, time * 1000)  
        }  
        this.taskList.unshift(fn);  
        return this;  
    }  
    next() {  
        var fn = this.taskList.shift();  
        fn && fn();  
    }  
}  
  
function LazyMan(name) {  
    return new LazyManClass(name);  
}  
  
LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TeeeT

我把常见问题分享,只为你懂

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值