文章出處

參考:http://www.cnblogs.com/rubylouvre/archive/2009/08/08/1541578.html

        function Person(){
            this.say =  function(name,lang){
                console.log("我的名字叫做"+name+",專注于"+lang+"...");
            }
        }
        
        (function() {
            //AOP(面向切面編程)的javaScript實現
            jsAOP = {
                /**
                 * target 切入的目標對象
                 * method 切入的目標函數(相對于target)
                 * advice 切入點執行函數
                 * **/
                before:function(target,method,advice){
                    //備份原函數
                    var original  = target[method];
                    target[method] = function(){
                        (advice)();
                        original.apply(target, arguments);
                    };
                    return target
                },
                after:function(target,method,advice){
                    var original  = target[method];
                    target[method] = function(){
                        original.apply(target, arguments);
                        (advice)();
                    };
                    return target
                },
                around:function(target,method,advice){
                    var original  = target[method];
                    target[method] = function(){
                        (advice)();
                        original.apply(target, arguments);
                        (advice)();
                    };
                    return target
                }
            };
        }());
        
        window.onload = function(){
            var p = new Person ();
            p = jsAOP.before(p,"say",function() {
                console.log("請你介紹一下自己!");
            });
            p = jsAOP.after(p,"say",function() {
                console.log("嗯,不錯,明天來上班吧!");
            });
            p = jsAOP.around(p,"say",(function() {
                var index = -1;
                return function() {
                    index++;
                    if(index == 0) {
                        console.log("介紹開始!");
                    }else{
                        console.log("介紹結束!");
                        index = -1;
                    }
                };
            }()));
            p.say("賴祥燃","javascript");
        };

參考:http://www.cnblogs.com/rubylouvre/archive/2009/08/08/1541578.html


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜

    大師兄 發表在 痞客邦 留言(0) 人氣()