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的修改,后者是对对象的方法修改

 

posted on 2014-08-25 10:12  山冈龙  阅读(197)  评论(0编辑  收藏  举报

导航