Open senfish opened 3 years ago
维护一个数组函数的队列,每个函数负责打印内容; 当所有的函数触发之后,再去执行数组函数
function GreetRobot(name) {
GreetRobot.prototype.listeners = [() => console.log(`Hi this is ${name}!`)]
setTimeout(() => {
GreetRobot.prototype.listeners.forEach(l => l())
})
return GreetRobot.prototype;
}
GreetRobot.prototype.listeners = [];
GreetRobot.prototype.greet = function (name) {
this.listeners.push(() => console.log(Nice to meet you ${name}
));
return this;
}
GreetRobot.prototype.greetVip = function (name) {
this.listeners.unshift(() => console.log(Glad to see you ${name}~
));
return this;
}
- es6利用类
```js
function GreetRobot(name) {
return new class {
constructor() {
this.listeners = [() => console.log(`Hi this is ${name}!`)];
this.run();
}
run() {
setTimeout(() => {
this.listeners.forEach(l => l());
}, 200)
}
greet(name) {
this.listeners.push(() => console.log(`Nice to meet you ${name}`))
return this;
}
greetVip(name) {
this.listeners.unshift(() => console.log(`Glad to see you ${name}~`))
return this;
}
}
}