题目
看到如下的一道题目,有点意思。一道题目包含了很多重要的JS知识点:this指向,闭包,事件轮询,链式调用,队列等。
实现一个LazyMan,可以按照以下方式调用:
LazyMan(“Hank”)输出:
Hi! This is Hank!
LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
Hi! This is Hank!
//等待10秒..
Wake up after 10
Eat dinner~
LazyMan(“Hank”).eat(“dinner”).eat(“supper”)输出
Hi This is Hank!
Eat dinner~
Eat supper~
LazyMan(“Hank”).sleepFirst(5).eat(“supper”)输出
//等待5秒
Wake up after 5
Hi This is Hank!
Eat supper
以此类推。
思考
- 为了链式调用,每个方法都需要返回this。
- 任务顺序需要使用队列来确认执行顺序
- 直接执行LazyMan就有输出,说明在构造时(constructor)就执行了输出,但sleepFirst可能先于这个输出,所以需要使用settimeout,利用Js的轮询机制,在主任务执行完毕后,调用next方法开始执行任务队列。
代码
有了思路,就可以着手写代码,详见注释。
1. ES5 prototype原型链
关键点在代码中注释。
// 定义_LazyMan构造函数
function _LazyMan(name){
let that = this // 定义that保存this,在返回的方法,或settimeout上下文环境变化的情况下,保证this指向正确
this.tasks = [] // 创建一个执行队列
this.tasks.push((n => { // 将方法push进执行队列
return function(){
console.log('Hi,this is ' + n + '!')
that.next() // 队列中的每个方法执行完毕后,执行next方法执行队列中下一个方法
}
})(name)) // 立即执行函数,可以返回一个带参数的function。
setTimeout(function(){that.next()},0) // settimeout可以让所有的链式方法执行完毕后,再开始执行队列。
}
// 使用prototype绑定方法,实现LazyMan.func()形式的调用
_LazyMan.prototype.next = function(){
var fn = this.tasks.shift() // 使用Array的shift方法,从队列中取出第一个值,队列也会相应缩短
fn && fn() // 如果取得到方法,则执行。
}
_LazyMan.prototype.eat = function(food){
let that = this
var fn = ((f) => {
return () => {
console.log('I eated ' + f + '!')
that.next()
}
})(food)
this.tasks.push(fn)
return this
}
_LazyMan.prototype.sleep = function(delay){
let that = this
var fn = (d => {
return () => {
setTimeout(() => {
console.log('I sleeped '+(d/1000)+'s')
that.next()
},d)
}
})(delay)
this.tasks.push(fn)
return that
}
_LazyMan.prototype.sleepFirst = function(delay){
let that = this
var fn = (d => {
return () => {
setTimeout(() => {
console.log('At first! sleep '+(d/1000)+'s')
that.next()
},d)
}
})(delay)
this.tasks.unshift(fn) //!! sleepFirst比较特殊,使用unshift把方法添加到队列最前,从而实现首先执行。
return this
}
// 工厂模式返回LazyMan
function LazyMan(name){
return new _LazyMan(name)
}
LazyMan('Eason').sleep(1000).eat('fish').eat('egg').sleep(500)
// At first! sleep 1s
// Hi,this is Eason!
// I eated fish!
// I eated egg!
// I sleeped 0.5s
2. ES6 Class改写
用ES6的Class特性修改明显变优雅很多。
class _LazyMan {
constructor(name){
let that = this
this.tasks = [],
this.fn = ((n)=>{
return ()=>{
console.log("this is "+ n +"!(By Class)")
that.next()
}
})(name)
this.tasks.push(this.fn)
setTimeout(() => {
that.next()
}, 0);
return this
}
next(){
var fn = this.tasks.shift()
fn && fn()
}
eat(food){
let fn = ((f)=>{
return ()=>{
console.log('eat '+ f)
this.next()
}
})(food)
this.tasks.push(fn);
return this
}
sleep(delay,immedia = false){
let that = this
let fn = ((d,i)=>{
return ()=>{
setTimeout(()=>{
console.log(`${i ? 'sleepFisrt ' : 'sleep '}` + (d/1000) + 's')
that.next()
},d)
}
})(delay,immedia)
immedia ? this.tasks.unshift(fn) : this.tasks.push(fn);
return this
}
sleepFirst(delay){
return this.sleep(delay,true)
}
}
let LazyMan = function (name){
return new _LazyMan(name)
}
LazyMan('').eat('fish').sleepFirst(1000).sleep(2000)
3. Promise实现
队列执行任务,Promise也有类似的属性,尝试用Promise实现。
参考:如何实现一个LazyMan
这个文章里的例子有小错误,修改后如下。用Promise实现LazyMan没有发挥Promise对于异步链式操作的方便性,反而让逻辑看起来很复杂,能实现,但并不好。
function _LazyMan(name){
this.orderPromise=this.newPromise(); // 定义顺序promise对象
this.insertPromise=this.newPromise(); // 定义插入promise对象
this.order(function(resolve){
console.log(name);
resolve();
})
}
_LazyMan.prototype={
/*实例化promise对象工厂*/
newPromise:function(){
return new Promise(function(resolve,reject){
resolve();
})
},
order:function(fn){
var self=this;
this.orderPromise=this.orderPromise.then(function(){
return new Promise(function(resolve,reject){
//如果有insertPromise,阻塞orderPromise.
if (self.fir) {
self.insertPromise.then(function(){
fn(resolve)
})
}else{
fn(resolve)
}
})
})
},
insert:function(fn){
var self=this;
this.fir=true;
this.insertPromise=this.insertPromise.then(function(){
return new Promise(function(resolve,reject){
fn(resolve);
self.fir=false;
})
})
},
firstTime:function(time){
let fn = resolve=>{
setTimeout(function(){
console.log('wait '+time+' s,other logic');
resolve();
},time*1000)
}
this.insert(fn);
return this;
},
eat:function(something){
let fn = resolve =>{
console.log(something+' ~~');
resolve();
}
this.order(fn);
return this;
},
sleep:function(time){
let fn = resolve =>{
setTimeout(function(){
console.log('sleep '+time+' s');
resolve();
},time*1000);
}
this.order(fn);
return this;
}
}
//接口封装。
function LazyMan(name) {
return new _LazyMan(name);
}
//调用测试
LazyMan('RoryWu').sleep(2).eat('dinner').eat('breakfast');
// 弹出:
// wait 1 s, other logic
// wait 3 s, other logic
// RoryWu
// sleep 2 s
// dinner~~
// breakfast~~