码迷,mamicode.com
首页 > Web开发 > 详细

JS实现AOP

时间:2014-08-25 11:27:44      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   art   div   cti   

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

 

JS实现AOP

标签:style   blog   color   io   for   ar   art   div   cti   

原文地址:http://www.cnblogs.com/shsgl/p/3934374.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!