按顺序输出:
实现fn:
1、fn(‘John’)
output: I am John
2、fn(‘John’).rest(10).learn(‘computer’)
output: I am John
// 等待10s:
Start learning after 10 seconds
Learning Computer
3、fn(‘John’).restFirst(5).learn(‘chinese’)
output:
// 等待5s
start learning after 5 seconds
I am John
Learing chinese
使用es6:class、 箭头函数
class fnName {
constructor(name) {
this.name = name
this.queue = []
const fn = ()=> {
console.log(`I am ${name}`)
this.next()
}
debugger
this.queue.push(fn)
setTimeout(() => {
this.next()
}, 0)
}
rest (time) {
const fn = () => {
setTimeout(() => {
console.log(`Start learning after ${time} ms`)
this.next()
}, time)
}
this.queue.push(fn)
return this
}
learn (sub) {
const fn = ()=> {
console.log(`Learning ${sub}`)
this.next()
}
this.queue.push(fn)
return this
}
restFirst (time) {
const fn = () => {
setTimeout(() => {
console.log(`Start learning after ${time} ms`)
this.next()
}, time)
}
this.queue.unshift(fn)
return this
}
next () {
const fn = this.queue.shift()
fn && fn()
}
}
function fn(name) {
return new fnName(name)
}
使用es5:
function fnClass (name) {
_this = this
this.name = name
this.queue = []
const fn = function () {
console.log(`I am ${name}`)
next()
}
next = function (){
const fn = _this.queue.length > 0 ? _this.queue.shift() : null
fn && fn.call(_this)
}
this.queue.push(fn)
setTimeout(function (){
next()
}, 0)
return _this
}
fnClass.prototype.rest = function (time) {
const _this = this
const fn = function () {
setTimeout(function () {
console.log(`Start learning after ${time} ms`)
next.call(_this)
}, time)
}
this.queue.push(fn)
return this
}
fnClass.prototype.learn = function (sub) {
const _this = this
const fn = function() {
console.log(`Learning ${sub}`)
next.call(_this)
}
this.queue.push(fn)
return this
}
function fn () {
return new fnClass('John')
}