// 惰性链
function LazyChain(obj) {
let isLC = (obj instanceof LazyChain) // 组合链,抽取调用链和目标对象
this._calls = isLC ? [...obj._calls] : []
this._target = isLC ? obj._target : obj
}
// 封装了一些行为的函数通常被称为thunk
LazyChain.prototype.invoke = function(methodName, ...args) {
this._calls.push(function(target) {
let meth = target[methodName]
return meth.apply(target, args)
})
return this
}
LazyChain.prototype.force = function() {
return this._calls.reduce((target, thunk) => {
return thunk(target)
}, this._target)
}
LazyChain.prototype.tap = function(fun) {
this._calls.push(function(target) {
fun(target)
return target
})
return this
}
let ret = new LazyChain([2, 1, 3]).invoke('sort').force()
console.log(ret)
ret = new LazyChain([2, 1, 3]).invoke('concat', [8, 7, 5, 6]).invoke('sort').invoke('join', ' ').force()
console.log(ret)
let deferredSort = new LazyChain([2, 1, 3]).invoke('sort').tap(x => console.log('alert'))
deferredSort.force()
ret = new LazyChain(deferredSort).invoke('toString').force()
console.log(ret)
惰性链和promise的区别:
高度耦合关联的任务、低耦合的任务。同步和异步。
缺点:
紧耦合对象的set和get(命令/查询)分离、尴尬命名问题
调用之间改变传递的共同引用