问题: 要求设计 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
- 首先需要了解constructor()函数
1. 是一种用于创建和初始化 class 的特殊方法
2. 在一个类中只能有一个 名为constructor的特殊函数,出现多个 constructor 函数会报一个 syntaxError 的错误。
3. 在此构造函数中可以使用 super 关键字来调用一个父类的构造方法
4. 如果没有显示指定构造方法,则会添加默认的 constructor 函数
- 了解什么是类。
1. 类是用于创建对象的模板
2. 类是特殊的函数,类语法有两个组成部分,一个是类表达式一个是类声明。
3. 函数声明和类声明不同的地方在于,类声明不会提升,函数声明会提升。
- 静态方法
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');