问题描述
类似Java AOP,抽出业务无关功能,再动态织入,可以保持业务逻辑纯净和高内聚
解决方案
可以使用高阶函数,重写Function.prototype,添加beforeFunction和afterFunction。
代码
Function.prototype.before = function(beforeFn) {const _self = this;return function() {beforeFn.apply(this, arguments);return _self.apply(this, arguments);}}Function.prototype.after = function(afterFn) {const _self = this;return function() {var ret = _self.apply(this, arguments);afterFn.apply(this, arguments);return ret;}}function fn() {console.log('2');}fn = fn.before(function(){console.log('1');}).after(function(){console.log('3');})fn();
