zoukankan      html  css  js  c++  java
  • 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);

      

      

  • 相关阅读:
    博客CSS样式 二
    产品经理
    HttpClient调用doGet、doPost、JSON传参及获得返回值
    Maven无法下载com.oracle:ojdbc.jar解决方法
    EasyExcel导入导出
    centos7 安装supervisor教程以及常见问题
    Django与Celery的安装使用
    亚马逊广告api v2版php扩展库
    Mac VMware Fusion CentOS7 安装、配置静态IP文档
    常见Web安全问题攻防解析
  • 原文地址:https://www.cnblogs.com/chenfengami/p/12548913.html
Copyright © 2011-2022 走看看