JavaScript AOP 使用

出处:https://www.cnblogs.com/zengyuanjun/p/7429968.html

/** * @desc 面向aop编程 * @param {Function} originFunc - 源方法 * @param {Function} before - 在源代码执行之前的方法体 * @param {Function} after - 在源代码执行之后的方法体 */ function constructor(originFunc, before, after) { return function() { before.apply(this, arguments); originFunc.apply(this, arguments); after.apply(this, arguments); } } function calcAdd(a, b) { console.log(a+b); return a + b; } // AOP增强 calcAdd = constructor(calcAdd, function() { console.log('add before'); }, function() { console.log('add after'); }); // 要求依次执行 add before 5 add after calcAdd(2, 3);



// AOP 工厂模式

var aopFactory = function(before, after) { // 构造方法,在原方法前后增加执行方法 function constructor(originFun){ function _class(){ proxy.before.apply(this, arguments); originFun.apply(this, arguments); proxy.after.apply(this, arguments); } return _class; } // 代理对象,a为被代理方法,b为目标对象 var proxy = { add: function(a, b) { var fnName = ''; if (typeof a === 'function') { fnName = a.name; } else if (typeof a === 'string') { fnName = a; } else { return; } // 不传对象的话默认为window b = b || window; if (typeof b === 'object' && b[fnName]) { b[fnName] = constructor(b[fnName]); } }, before: function() { }, after: function() { } }; if (typeof before === 'function') { proxy['before'] = before; } if (typeof after === 'function') { proxy['after'] = after; } return proxy; } var printProxy, checkProxy; // 打印参数 function printArguments(){ for(var i = 0; i < arguments.length; i++){ console.info("param" + (i + 1) + " = " + arguments[i]); } } // 打印和 function printSum() { var sum = 0; for(var i = 0; i < arguments.length; i++){ sum += arguments[i]; } console.log('和', sum); } // 传入一个打印参数的AOP前增强 printProxy = aopFactory(printArguments, printSum); function calcAdd(a, b) { return a + b; } // 传入需要增强的原方法 printProxy.add(calcAdd); calcAdd(1, 2);

  

  

posted @ 2020-03-22 22:25  chenfengami  阅读(306)  评论(0编辑  收藏  举报