zoukankan      html  css  js  c++  java
  • JS实现AOP

    JS实现AOP  


     

    <script>
    function actsAsAspect(obj,handlers) {
            if(typeof obj == 'function'){
                obj = obj.prototype;
            }
            
            for(var methodName in handlers){
                var _handlers = handlers[methodName];
                for(var handler in _handlers){
                    if((handler == 'before' || handler == 'after') && typeof _handlers[handler] == 'function'){
                        eval_r(handler)(obj,methodName,_handlers[handler]);
                    }
                }
            }

            function before(obj,method,f) {
                var original = obj[method];   
                obj[method] = function() {
                    f.apply(this, arguments);   
                    return original.apply(this, arguments);   
                }
            }

            function after(obj,method, f) {   
                var original = obj[method];   
                obj[method] = function() {
                    original.apply(this, arguments);   
                    return f.apply(this, arguments);   
                }
            }
        }
        
        //actsAsAspect(Test,{'say2':{before:function(){alert('before');},after:function(){alert('after');}}});   
        
        function Test(){}   

        //actsAsAspect(Test,{'say2':{before:function(){alert('before');},after:function(){alert('after');}}});   

        Test.prototype.say2 = function(s){
            alert(s);
        }
        
        actsAsAspect(Test,{'say2':{before:function(){alert('before');},after:function(){alert('after');}}});   

        var t = new Test(); 

        //actsAsAspect(t,{'say2':{before:function(){alert('before');},after:function(){alert('after');}}});  
        t.say2("hello2"); 

    </script>

    由于新浪的编辑器太差了,把eval_r改成eval就可以运行了

    支持对Class 和 Object 两种类型的AOP,前者是基于对prototype的修改,后者是对对象的方法修改

  • 相关阅读:
    解题报告:POJ1852 Ants
    解题报告:POJ2573 Bridge(分析建模)
    POJ 3321 Apple Tree(树状数组模板)
    PAT1139 First Contact
    POJ3259 SPFA判定负环
    HDOJ2586 最近公共祖先模板
    树的直径与最近公共祖先
    字符数组_随机存储
    青鸟资料下载
    软件测试(4)_LoadRunner使用
  • 原文地址:https://www.cnblogs.com/shsgl/p/3934374.html
Copyright © 2011-2022 走看看