Last active
November 3, 2019 09:55
-
-
Save ifyour/9fa5fa702f3b294a92ee37656829e310 to your computer and use it in GitHub Desktop.
巧妙扩展 Function 原型,实现职责链模式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// eslint-disable-next-line no-extend-native | |
Function.prototype.after = function(fn) { | |
const _this = this; | |
return function() { | |
const ret = _this.apply(this, arguments); | |
if (ret === 'nextSuccessor') { | |
return fn.apply(this, arguments); | |
} | |
return ret; | |
} | |
} | |
// 函数 A 若无法满足需求,交给函数 B,函数 B 无法满足需求交给 C,以此类推 | |
// 解耦合,同时能自定义该链条(新增、删除、重组) | |
const doSome = A.after(B).after(C); | |
doSome(); | |
function A() { | |
if ('some condition') { | |
// 业务逻辑 | |
} | |
return 'nextSuccessor'; | |
} | |
function B() { | |
if ('some condition') { | |
// 业务逻辑 | |
} | |
return 'nextSuccessor'; | |
} | |
function C() { | |
if ('some condition') { | |
// 业务逻辑 | |
} | |
return 'nextSuccessor'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment