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

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。